面试题答案
一键面试实现CSS变量与JavaScript的有效交互
- 通过
document.documentElement.style
读写- 读取:在JavaScript中,可以通过
document.documentElement.style.getPropertyValue('--variable-name')
来获取CSS变量的值。例如,假设CSS中有:root { --primary-color: blue; }
,在JavaScript中可以这样获取:
- 读取:在JavaScript中,可以通过
const primaryColor = document.documentElement.style.getPropertyValue('--primary-color');
console.log(primaryColor);
- 写入:使用
document.documentElement.style.setProperty('--variable - name', 'new - value')
来设置CSS变量的值。比如要改变上述--primary - color
的值:
document.documentElement.style.setProperty('--primary-color','red');
- 使用
CSSStyleDeclaration
对象- 可以通过获取元素的
style
属性,它是一个CSSStyleDeclaration
对象,同样可以对CSS变量进行读写。例如,对于一个具有id
为myElement
的元素:
- 可以通过获取元素的
<div id="myElement" style="--secondary - color: green;"></div>
const myElement = document.getElementById('myElement');
const secondaryColor = myElement.style.getPropertyValue('--secondary - color');
myElement.style.setProperty('--secondary - color', 'yellow');
频繁更新CSS变量值的性能优化
- 批量更新
- 避免频繁单个更新CSS变量,而是将多个更新操作合并在一起。例如,假设要更新多个CSS变量
--width
、--height
和--color
:
- 避免频繁单个更新CSS变量,而是将多个更新操作合并在一起。例如,假设要更新多个CSS变量
// 不好的方式,多次触发重排重绘
document.documentElement.style.setProperty('--width', '100px');
document.documentElement.style.setProperty('--height', '200px');
document.documentElement.style.setProperty('--color','red');
// 好的方式,批量更新
const style = document.documentElement.style;
style.setProperty('--width', '100px');
style.setProperty('--height', '200px');
style.setProperty('--color','red');
- 使用
requestAnimationFrame
- 当更新CSS变量会引起动画或者视觉变化时,可以使用
requestAnimationFrame
。它会在浏览器下一次重绘之前执行回调函数。例如,要实现一个渐变效果,逐渐改变--opacity
变量的值:
- 当更新CSS变量会引起动画或者视觉变化时,可以使用
let opacity = 0;
function updateOpacity() {
opacity += 0.1;
if (opacity > 1) {
opacity = 1;
}
document.documentElement.style.setProperty('--opacity', opacity);
if (opacity < 1) {
requestAnimationFrame(updateOpacity);
}
}
requestAnimationFrame(updateOpacity);
- 利用CSS transitions 和 animations
- 对于一些过渡效果,优先使用CSS的
transition
和animation
属性,而不是频繁用JavaScript更新CSS变量。例如,要实现一个元素在改变--primary - color
时的渐变过渡:
- 对于一些过渡效果,优先使用CSS的
:root {
--primary - color: blue;
transition: --primary - color 0.3s ease - in - out;
}
- 然后在JavaScript中更新
--primary - color
变量时,就会有一个平滑的过渡效果,而不会造成突兀的重排重绘。
实际案例
假设我们有一个简单的网页,页面中有一个按钮,点击按钮可以切换主题颜色。
<!DOCTYPE html>
<html lang="en">
<head>
<style>
:root {
--primary - color: blue;
}
body {
background - color: var(--primary - color);
}
</style>
</head>
<body>
<button id="themeButton">切换主题颜色</button>
<script>
const themeButton = document.getElementById('themeButton');
themeButton.addEventListener('click', function () {
const currentColor = document.documentElement.style.getPropertyValue('--primary - color');
const newColor = currentColor === 'blue'? 'green' : 'blue';
// 批量更新(虽然这里只有一个变量更新,但体现思路)
const style = document.documentElement.style;
style.setProperty('--primary - color', newColor);
});
</script>
</body>
</html>
在这个案例中,通过点击按钮更新 --primary - color
变量,并且使用了批量更新的方式(虽然只有一个变量更新,但体现了这种优化思路),这样在一定程度上避免了频繁更新带来的性能损耗。