JQuery Detect类更改
我正在使用一个插件,在open
添加了一个open
.slide-out-div
的类。
所以我试图改变一些css如果检测到打开。
我需要做的是
IF $('.slide-out-div **open**') IS Detected then $('.otherDiv').css('top','0px');
不知道怎么把它们放在一起……
没有class-added
事件,您需要自己跟踪…
可以使用setTimeout
进行无限循环来检查类是否已更改。
function checkForChanges() { if ($('.slide-out-div').hasClass('open')) $('.otherDiv').css('top','0px'); else setTimeout(checkForChanges, 500); }
您可以在需要时调用该函数,或者在onDOM就绪时调用:
$(checkForChanges);
这个问题有点老了,但是因为我在寻找类似的问题时遇到了,我想我会分享我在这里遇到的解决方案 – Mutation Observers
在你的情况下,我会创建一个变异观察者
var mut = new MutationObserver(function(mutations, mut){ // if attribute changed === 'class' && 'open' has been added, add css to 'otherDiv' }); mut.observe(document.querySelector(".slide-out-div"),{ 'attributes': true });
每当.slide-out-div的属性发生变化时,都会调用变异观察器中的函数,因此需要在执行之前validation实际变化。
有关Mozilla文档页面的更多详细信息
你可以使用attrchange jQuery插件 。 插件的主要function是在HTML元素的属性更改上绑定侦听器函数。
代码示例:
$("#myDiv").attrchange({ trackValues: true, // set to true so that the event object is updated with old & new values callback: function(evnt) { if(evnt.attributeName == "class") { // which attribute you want to watch for changes if(evnt.newValue.search(/open/i) == -1) { // "open" is the class name you search for inside "class" attribute // your code to execute goes here... } } } });