对于以下元素,我正在尝试检测内联样式更改:
<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/