jquery - 通过 JQuery 检测元素上的内联样式/CSS 更改

标签 jquery html css

对于以下元素,我正在尝试检测内联样式更改:

<div class="webform-component--personal-details" style="display: none;">
 <p> This that this that.</p>
</div>

在上面的示例中,style 可以是 style="display: none;"style="display: block;" 这是我尝试过的方法,但没有用:

$('.webform-component--personal-details').on('stylechanged', function () {
    console.log('css changed');
});

最佳答案

如果你想在调用 jQuery 的 css 函数后触发 stylechanged 事件,那么你应该首先重写 css 函数作为@MikeAllen和@ccsakuweb 在他们的答案中写了 here & here :

// Extends functionality of ".css()"
// This could be renamed if you'd like (i.e. "$.fn.cssWithListener = func ...")
(function() {
    orig = $.fn.css;
    $.fn.css = function() {
        var result = orig.apply(this, arguments);
        $(this).trigger('stylechanged');
        return result;
    }
})();


// Add listener
$('div#box').on('stylechanged', function () {
    console.log('stylechanged: ','The css changed');
});

$('button').on('click',function(){
  // Perform change
  $('div#box').css('background', 'red');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="box" style="background:blue;height:100px;"></div>
<button>Change Color</button>

或者

使用 MutationObserver 不需要 jQuery,正如@codebox 在他的回答中提到的 here :

var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutationRecord) {
        console.log('style changed:',mutationRecord);
    });    
});

var target = document.getElementById('box');
observer.observe(target, { attributes : true, attributeFilter : ['style'] });


function changeColor() {
  document.getElementById("box").style="background:red;height:100px;";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="box" style="background:blue;height:100px;"></div>
<button onclick="changeColor()">Change Color</button>

关于jquery - 通过 JQuery 检测元素上的内联样式/CSS 更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56813455/

相关文章:

css - 为什么不溢出: hidden work with material icons?

html - 内容超过页脚

css - 旁路溢出 :hidden position:relative of layout ancestor

html - 如何告诉 chrome 不要为文本框提供建议

jquery - 如何使用自动时间换类

javascript - jquery 的 every() 在 Internet Explorer 上不起作用

jquery - 当我使用自定义选择框时按钮位置尴尬

html - CSS 异常行为 : overflow and margin-left

html - 使用 Bootstrap 布局网格

javascript - 获取一个 asp radiobuttonlist 通过 jquery 触发它的 TextChanged 事件?