我已经浏览了多个示例,并实现了示例所述的相同行为。
页面加载后,如果 dom 元素的样式发生变化,我需要触发一个方法。
即使我在浏览器控制台中更改任何内容,样式更改事件也应该触发。该事件将显示为“无”和“显示块”。
在我的代码中,如果在浏览器控制台中进行更改,则不会触发更改方法。
这是我尝试过的:
(function() {
var ev = new $.Event('style'),
orig = $.fn.css;
$.fn.css = function() {
var ret = orig.apply(this, arguments);
$(this).trigger(ev);
return ret;
}
})();
$('p').bind('style', function(e) {
console.log($(this).attr('style'));
});
p {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p> test </p>
你可以使用变异观察者 https://developer.mozilla.org/en/docs/Web/API/MutationObserver:
Demo:
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
var oldDisplay = (mutation.oldValue + '').match(/display:\s*(\w*)/);
oldDisplay = oldDisplay ? oldDisplay[1] : '';
if (oldDisplay !== mutation.target.style.display) {
console.log('element', mutation.target.id,
'style.display=', mutation.target.style.display);
}
});
});
// attach the observer to the elements of interest:
$('p').each(function () {
observer.observe(this, {
attributes: true,
attributeFilter: ['style'],
attributeOldValue: true
});
});
// test it, by changing style.display through button clicks:
$('button').click(function() {
$('p').toggle(); // show/hide
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="p1"> test this </p><button>hide/show</button>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)