javascript - 在悬停选择器更改之前获取元素样式
问题描述
我正在尝试制作一个 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
更改之前的背景颜色(在这种情况下为红色、黄色或绿色)。
解决方案
只需将元素替换为自身,这会强制更新悬停状态,然后计算样式:
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>
推荐阅读
- angular - 我可以为 angular/typescript 中的导入库提供别名吗?
- intellij-idea - 如何在 IntelliJ 项目中添加新包?
- speech-recognition - 不能识别除英语以外的其他语言的句子
- android - 在布局 xml 中定义 Android 标签不起作用
- c - 如何在cmake窗口中添加资源
- amazon-web-services - 通过网关 websocket 调用长时间运行的 Lambda 的最简单方法是什么?
- c++ - 尝试初始化静态方法时出现错误“方法在此上下文中是私有的”
- swift - iOS GCD 同步和异步
- python-3.x - AxisError:轴 1 超出维度 1 数组的范围 - np.concatenate()
- sql - 查找学习两个具有三个不同角色 SQL 的科目的学生