javascript jQuery(event):监视元素样式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4567987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery(event): watch element style
提问by GusDeCooL
let say have element like this
假设有这样的元素
<div class="watch-me" style="display: none;">Watch Me Please</div>
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: blockthen there is some code will be trigger.
正如我们可以看到上面样式的元素display: none,我如何制作脚本来观看这个元素。当该元素样式更改display: block为时,将触发一些代码。
many thanks...
非常感谢...
回答by Jacob Relkin
As far as I know, the only way to do this would be with a timer.
据我所知,做到这一点的唯一方法是使用计时器。
I created a small jQuery plugin (yes, right here, right now) that does this against a jQuery set:
我创建了一个小型 jQuery 插件(是的,就在这里,现在),它针对 jQuery 集执行此操作:
EDITthis plugin is now on GitHub: https://github.com/jacobrelkin/jquery-watcher
编辑此插件现在在 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);
});
};
Usage:
用法:
$('.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...
}
});
To clear this property watcher:
要清除此属性观察器:
$('.watch-me').unwatch('style');
回答by Amjad Masad
You may use object.watchfunction however its non standard, there is already a cross-browser implementation Object.watch() for all browsers?
你可以使用object.watch函数但是它不是标准的,已经有一个跨浏览器的实现Object.watch() 适用于所有浏览器?
$('.watch-me').get(0).watch('style', handlerFunction);
回答by Roman
function startPolling()
{
var handle = window.setInterval(function(){
var element = $(".watch-me");
if (element.css("display") == "block") {
// trigger the event
window.clearInterval(handle);
}
}, 100);
}
When you want to start watching simply write:
当您想开始观看时,只需编写:
startPolling();
回答by Xaxis
I wrote a jQuery plugin for watching changes on DOM element properties/attributes and CSS properties that some might find more intuitive/easier to use: jQuery.watch
我写了一个 jQuery 插件,用于观察 DOM 元素属性/属性和 CSS 属性的变化,有些人可能会发现它们更直观/更易于使用:jQuery.watch
In order to accomplish what you're after you would do something like this:
为了完成你所追求的,你会做这样的事情:
$('.watch-me').watch({
'display': function( oldVal, newVal, elm ) {
if (newVal == 'block') {
// Do something
}
}
});
The plugin also supports tracking the return values of jQuery methods on watched elements, so you could for instance fire a callback when the return value of a jQuery method changes when called on a given element.
该插件还支持在监视元素上跟踪 jQuery 方法的返回值,例如,当在给定元素上调用 jQuery 方法的返回值更改时,您可以触发回调。
回答by Phrogz
Since you can't rely on the DOM Mutation Eventsdue to no support for IE before 9, I thinkyou'll be required to set a polling timer to watch. For example:
由于在 9 之前不支持 IE,您不能依赖DOM Mutation Events,因此我认为您需要设置一个轮询计时器来观看。例如:
var watched = $('.watch-me');
var lastDisplay = watched.css('display');
// Peek at the property about twice per second
setInterval(function(){
var curDisplay = watched.css('display');
if (curDisplay!=lastDisplay){
// Do what you want here.
lastDisplay = curDisplay;
}
},500);
If you want to cancel the watching after it changes once:
如果您想在更改一次后取消观看:
var watched = $('.watch-me');
var lastDisplay = watched.css('display');
var timer = setInterval(function(){
if (watched.css('display')!=lastDisplay){
// Do what you want here.
clearInterval( timer );
}
},500);
回答by Paul B. Hartzog
This might be considered not answering the question, but it would be better to use JQuery custom events and the .trigger method than using intervals and watching (which just consumes resources).
这可能被认为没有回答问题,但使用 JQuery 自定义事件和 .trigger 方法比使用间隔和观察(这只会消耗资源)更好。
More to the point, elements can subscribe to new triggered events from objects that they are "watch"ing.
更重要的是,元素可以从它们正在“观察”的对象订阅新的触发事件。
Take a look here:
看看这里:
回答by Konstantin Eletskiy
check https://developer.mozilla.org/en/docs/Web/API/MutationObserver
检查https://developer.mozilla.org/en/docs/Web/API/MutationObserver
var target = _DOM_;
var lastDisplayStyle = _DOM_.style.display;
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
if (mutation.type === "attributes") {
if (lastDisplayStyle !== _DOM_.style.display){
// your code there
}
}
});
});
var config = { attributes: true };
observer.observe(target, config);
P.S. watch / unwatch are deprecated. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/watchDo not use setInterval solutions!
PS watch / unwatch 已弃用。 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/watch不要使用 setInterval 解决方案!
回答by karim79
This is highly experimental (you have been warned!) and might not be a good fit to your problem or answer to this question, but it has occurred to me that you can do two things:
这是高度实验性的(您已被警告!)并且可能不适合您的问题或此问题的答案,但我突然想到您可以做两件事:
1 - Override the jQuery's core .togglemethod to add some data to the elements it gets applied to.
1 - 覆盖 jQuery 的核心.toggle方法,将一些数据添加到应用到的元素中。
2 - Bind a changeDataevent handler to elements, as of jQuery 1.4.4
2 -changeData从 jQuery 1.4.4 开始,将事件处理程序绑定到元素
What that means is, you can make something happen whenever an element gets toggled. The same principle could apply to the .hideand .showmethods, or any other methods for that matter.
这意味着,只要元素被切换,您就可以使某些事情发生。相同的原则可以适用于.hide和.show方法,或任何其他与此相关的方法。
// 1 - override .toggle()
var original = jQuery.fn.toggle;
jQuery.fn.toggle = function() {
console.log("Override method: toggle()");
// call the original toggle
original.apply(this, arguments);
// record the element's visibility
$(this).data("visible", $(this).is(":visible"));
return this;
};
// 2 - bind a changeData event handler to a 'watch list'
$('div').bind("changeData", function() {
alert("Visibility changed to: " + $.data(this, 'visible'));
});
<!-- exhaustive test markup -->
<div id="test">Hello</div>
<div id="test2" style="display:none">Hello 2</div>
// go!
$(document).ready(function() {
$("#test").toggle();
$("#test2").toggle();
});
Try it out here: http://jsfiddle.net/karim79/nreqv/1/

