[英]How to select css variable and assign style value to another element
我正在尋找一種方法來 select css 變量--bgcolor
被懸停的元素並將該值分配給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()
與 computedStyle 一起使用。 否則你可以直接從computedStlye獲取background
屬性
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>
您可以通過getComputedStyle
和getPropertyValue
方法訪問 Javascript 代碼中的 CSS 變量,如下所示:
getComputedStyle(el).getPropertyValue('--bgcolor');
因此,在您的情況下,將newbg
設置為上面的行而不是el.style.background
。
如果您在實施我的解決方案時遇到任何問題或疑問,請在評論中告訴我。
編輯:看起來有人打了我一拳!
我會委托
const body = document.querySelector('body'); const bodyCol = window.getComputedStyle(body).getPropertyValue('--bgcolor') const hover = e => { const tgt = e.target; if (tgt.classList.contains("box")) { const bg = window.getComputedStyle(tgt).getPropertyValue('--bgcolor') body.style.backgroundColor = e.type === "mouseover"? bg: bodyCol; } }; document.getElementById("colors").addEventListener("mouseover",hover) document.getElementById("colors").addEventListener("mouseout",hover)
body { background: var(--bgcolor); }.box { width: 80px; height: 80px; margin: 10px; background: var(--bgcolor); display:inline-block; }
<body> <div id="colors"> <div class="box" style="--bgcolor: #FF0000"></div> <div class="box" style="--bgcolor: #00FF00"></div> <div class="box" style="--bgcolor: #0000FF"></div> </div> </body>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.