首页 > 解决方案 > 在悬停选择器更改之前获取元素样式

问题描述

我正在尝试制作一个 chrome 扩展来查找按下元素的原始背景颜色。
我的意思是用户悬停之前:hover的背景颜色,选择器(也许)改变了它。
我尝试使用document.styleSheets,但它给了我一个错误

例子

window.addEventListener("click",function(e){
  pressedElement = e.target;
  console.log(window.getComputedStyle(pressedElement,null).backgroundColor);
  //return blue but I want the background before hover changes (green,yellow,red in this case)
});
div{
  height:100px;
  width:100px;
}
div:hover{
  background-color:blue !important;
}
<div style="background-color:green;">1</div>
<div style="background-color:yellow;">2</div>
<div style="background-color:red;">3</div>
window.getComputedStyle(pressedElement,null).backgroundColor返回当前的背景颜色(在这种情况下为蓝色),但我想要:hover更改之前的背景颜色(在这种情况下为红色、黄色或绿色)。

标签: javascriptdomgoogle-chrome-extension

解决方案


只需将元素替换为自身,这会强制更新悬停状态,然后计算样式:

window.addEventListener("click",function(e){
  const target = e.target;
  target.parentNode.replaceChild(target, target)
  const color = window.getComputedStyle(target,null).backgroundColor;
  console.log(color);
  return color;
});
div{
  height:100px;
  width:100px;
}
div:hover{
  background-color:blue !important;
}
<div style="background-color:green;">1</div>
<div style="background-color:yellow;">2</div>
<div style="background-color:red;">3</div>


推荐阅读