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

时间:2019-06-28 21:46:33

标签: jquery html css

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

<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');
});

1 个答案:

答案 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>

相关问题