【发布时间】:2021-08-05 20:32:20
【问题描述】:
我需要检测 css 上的变化,但我需要样式属性(宽度、高度、背景颜色……等)作为变量,仅表示已更改的那个。所以我不需要价值。我需要一个变量形式的样式属性,例如粗体:
document.getElementById ('id1')。 style.backgroundColor = '红色';
document.getElementById ('id1')。 style.颜色 = '红色';
我尝试使用 MutationObserver(可能是一些样式过滤器)...或者也许还有其他方法如何获取样式属性?
<h1 id="id1" style="background-color:green;color:blue;">My Heading 1</h1>
<button type="button"
onclick="document.getElementById('id1').style.color = 'yellow'">
Click Me!</button>
<button type="button"
onclick="document.getElementById('id1').style.backgroundColor = 'red'">
Click Me!</button>
const Observep = document.getElementById("id1");
const observerp = new MutationObserver(function() {
// var styleproperty = (backgroundColor or color or width....)
alert("id1 chenge" + styleproperty);
});
observerp.observe(Observep, {subtree: true, attributes: true});
【问题讨论】:
-
你应该可以用 MutationObserver 做到这一点:
.attributeName === 'style'.
标签: javascript css properties return-value mutation-observers