【问题标题】:Detect changed style property?检测更改的样式属性?
【发布时间】: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


【解决方案1】:

试试这个,

<button type="button" onclick="addStyle()"> Click Me!</button>


<script type="text/javascript">

    const elem = document.getElementById("id1");
    var setStyle = { 
        backgroundColor:'green',
        color:'blue',
      }

    function addStyle (){
      for(let prop of Object.keys(setStyle)){
        console.log(prop);
        elem.style[prop.toString()] = setStyle[prop.toString()];
      }
    }

</script>

【讨论】:

    【解决方案2】:

    我相信这就是您正在寻找的:

    const Observep = document.getElementById("id1");
    
    var observer = new MutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
        //console.log(mutation.target.style)
        let styles = mutation.target.style;
        for(style of styles){
          console.log(style)
        }
        if(mutation.attributeName === 'style'){
          alert("style change");
        }
      });    
    });
    
    // Notify me of style changes
    var observerConfig = {
      attributes: true, 
      attributeFilter: ["style"]
    };
    
    observer.observe(Observep, observerConfig);
    <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>

    【讨论】:

    • 我不需要属性(样式),我需要样式的哪一部分发生了变化:颜色、宽度、背景颜色等...
    猜你喜欢
    • 2012-04-25
    • 1970-01-01
    • 2013-03-28
    • 1970-01-01
    • 1970-01-01
    • 2011-12-10
    • 2013-11-04
    • 1970-01-01
    • 2015-02-14
    相关资源
    最近更新 更多