将鼠标悬停在某个元素上时,获取该元素的默认计算CSS样式



我正在尝试构建一个工具来收集网页上任何元素的CSS样式。出现的问题是,您需要将鼠标悬停在元素上才能选择它,但在这样做的同时,它会触发:悬停状态。

理想情况下,我希望收集默认样式和:hover样式,这似乎可以通过传递带有getComputedStyle的psuedo元素来实现。如果可能的话,我希望这样做的方法是暂时禁用:悬停,然后直接通过getComputedStyle获得默认状态和悬停状态。我曾尝试在悬停在该元素上时为其提供pointer-events: none的CSS属性,但这非常奇怪,不允许选择该元素,只允许选择父元素。

这是我目前正在使用的一小段代码。

document.body.addEventListener('mouseover', function(e) {
var targetElement = e.target;
var allStyles = getComputedStyle(e.target);
});

我还尝试并收集了一个元素的classList,将所有CSS样式应用于这些类,但对于任何一个属性"background color",都有多个冲突的样式,我不知道哪个样式实际应用于该元素。有没有办法对此进行检查或暂时禁用悬停状态?

非常感谢您的观看!

使用目标relatedTarget

document.addEventListener("mouseover", handle);
function handle(evt) {
if (evt.target.id === "foo") {
console.clear();
const currentStyle = getComputedStyle(evt.relatedTarget);
console.log(currentStyle.color, currentStyle.cursor);
}
}
#foo {
margin: 2rem;
}
#foo:hover {
color: red;
cursor: pointer;
}
<div id="foo">Hi there</div>

最新更新