Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

javascript - 是否可以听“风格改变”事件?(Is it possible to listen to a “style change” event?)

Is it possible to create an event listener in jQuery that can be bound to any style changes?(是否可以在jQuery中创建可以绑定到任何样式更改的事件侦听器?)

For example, if I want to "do" something when an element changes dimensions, or any other changes in the style attribute I could do:(例如,如果我想在元素更改尺寸或对style属性进行任何其他更改时“执行”操作,则可以执行以下操作:) $('div').bind('style', function() { console.log($(this).css('height')); }); $('div').height(100); // yields '100' It would be really useful.(这将非常有用。) Any ideas?(有任何想法吗?) UPDATE(更新) Sorry for answering this myself, but I wrote a neat solution that might fit someone else:(很抱歉自己回答这个问题,但是我写了一个可能适合其他人的简洁解决方案:) (function() { var ev = new $.Event('style'), orig = $.fn.css; $.fn.css = function() { $(this).trigger(ev); return orig.apply(this, arguments); } })(); This will temporary override the internal prototype.css method and the redefine it with a trigger at the end.(这将临时覆盖内部prototype.css方法,并在最后使用触发器重新定义它。) So it works like this:(所以它是这样的:) $('p').bind('style', function(e) { console.log( $(this).attr('style') ); }); $('p').width(100); $('p').css('color','red');   ask by David Hellsing translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Things have moved on a bit since the question was asked - it is now possible to use a MutationObserver to detect changes in the 'style' attribute of an element, no jQuery required:(自从提出此问题以来,事情一直在发展-现在可以使用MutationObserver来检测元素的'style'属性中的更改,而无需jQuery:)

var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutationRecord) { console.log('style changed!'); }); }); var target = document.getElementById('myId'); observer.observe(target, { attributes : true, attributeFilter : ['style'] }); The argument that gets passed to the callback function is a MutationRecord object that lets you get hold of the old and new style values.(传递给回调函数的参数是MutationRecord对象, 对象可让您掌握新旧样式值。) Support is good in modern browsers including IE 11+.(包括IE 11+在内的现代浏览器中,支持很好 。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...