对于以下元素,我正在尝试检测内联样式更改:
<div class="webform-component--personal-details" style="display: none;">
<p> This that this that.</p>
</div>
在上面的示例中,样式可以是 style =“ display:none;” 或 style =“ display:block;” 这是我尝试过的方法,但是没有用:
$('.webform-component--personal-details').on('stylechanged', function () {
console.log('css changed');
});
答案 0 :(得分:0)
如果您要在调用stylechanged
的css函数后触发jQuery
事件,则应首先覆盖css
函数,因为@MikeAllen和@ccsakuweb已在其答案中写出了{ {3}}和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,就像他的答案here中提到的@codebox:
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>