jQuery(event):表单元素样式 [英] jQuery(event): watch element style
本文介绍了jQuery(event):表单元素样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我们说这样的元素
<div class="watch-me" style="display: none;">Watch Me Please</div>
我们可以看到上面的元素是 display:none
,我该怎么做脚本来观看这个元素。当元素样式更改为 display:block
然后有一些代码将被触发。
as we can see the element above style is display: none
, how can i make script to watch this element. when that element style is change to display: block
then there is some code will be trigger.
很多谢谢。
推荐答案
据我所知,这样做的唯一方法是使用定时器。
As far as I know, the only way to do this would be with a timer.
我创建了一个小的jQuery插件(是的,就在这里,现在),这是针对一个jQuery集合:
I created a small jQuery plugin (yes, right here, right now) that does this against a jQuery set:
EDIT 此插件现在在GitHub上: https://github.com/jacobrelkin/jquery-观察者
EDIT this plugin is now on GitHub: https://github.com/jacobrelkin/jquery-watcher
$.fn.watch = function(property, callback) {
return $(this).each(function() {
var self = this;
var old_property_val = this[property];
var timer;
function watch() {
if($(self).data(property + '-watch-abort') == true) {
timer = clearInterval(timer);
$(self).data(property + '-watch-abort', null);
return;
}
if(self[property] != old_property_val) {
old_property_val = self[property];
callback.call(self);
}
}
timer = setInterval(watch, 700);
});
};
$.fn.unwatch = function(property) {
return $(this).each(function() {
$(this).data(property + '-watch-abort', true);
});
};
用法:
$('.watch-me').watch('style', function() {
//"this" in this scope will reference the object on which the property changed
if($(this).css('display') == 'block') {
//do something...
}
});
要清除此属性观察者:
$('.watch-me').unwatch('style');
这篇关于jQuery(event):表单元素样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文