【问题标题】:Get element style before hover selector changes在悬停选择器更改之前获取元素样式
【发布时间】:2020-07-02 11:17:40
【问题描述】:

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

示例

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 更改之前的背景色(本例中为红色、黄色或绿色)。

【问题讨论】:

    标签: javascript dom google-chrome-extension


    【解决方案1】:

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

    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>

    【讨论】:

      猜你喜欢
      • 2011-11-18
      • 1970-01-01
      • 2019-07-31
      • 1970-01-01
      • 2011-10-21
      • 1970-01-01
      • 1970-01-01
      • 2020-01-24
      • 1970-01-01
      相关资源
      最近更新 更多