我正在寻找一种方法来选择--bgcolor
要悬停的元素的css变量并将该值分配给body
css
这是我目前的尝试,有什么建议吗?
var body = document.querySelector('body');
var boxList = document.querySelectorAll('.box');
var box = Array.prototype.slice.call(boxList);
box.forEach(function (el) {
el.addEventListener('mouseover', ()=> {
var newbg = el.style.background;
body.style.background = newbg;
});
});
body {
background: var(--bgcolor);
}
.box {
width: 80px;
height: 80px;
margin: 10px;
background: var(--bgcolor);
display:inline-block;
}
<body>
<div class="box" style="--bgcolor: #FF0000"></div>
<div class="box" style="--bgcolor: #00FF00"></div>
<div class="box" style="--bgcolor: #0000FF"></div>
</body>
您可以使用getComputedStyle()
。如果要获取变量,则需要getPropertyValue()
与computeStyle一起使用。否则,您可以直接background
从calculatedStlye获取属性
var body = document.querySelector('body');
var boxList = document.querySelectorAll('.box');
var box = Array.prototype.slice.call(boxList);
box.forEach(function (el) {
el.addEventListener('mouseover', ()=> {
var newbg = window.getComputedStyle(el).getPropertyValue('--bgcolor')
body.style.background = newbg;
});
});
body {
background: var(--bgcolor);
}
.box {
width: 80px;
height: 80px;
margin: 10px;
background: var(--bgcolor);
display:inline-block;
}
<body>
<div class="box" style="--bgcolor: #FF0000"></div>
<div class="box" style="--bgcolor: #00FF00"></div>
<div class="box" style="--bgcolor: #0000FF"></div>
</body>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句