有没有一种方法可以检测元素的“ display” css属性是否已更改(更改为none还是block或inline-block ...)?如果没有,有插件吗?谢谢
Answers:
注意
是的你可以。DOM L2事件模块定义了突变事件;其中之一-DOMAttrModified是您需要的。当然,它们并未得到广泛实施,但至少在Gecko和Opera浏览器中受支持。
尝试以下方法:
document.documentElement.addEventListener('DOMAttrModified', function(e){
if (e.attrName === 'style') {
console.log('prevValue: ' + e.prevValue, 'newValue: ' + e.newValue);
}
}, false);
document.documentElement.style.display = 'block';
您也可以尝试利用IE的“ propertychange”事件代替DOMAttrModified。它应该允许style可靠地检测更改。
class元素祖先的属性(如果CSS中存在属性选择器,则更改任何其他属性)也可能会更改元素,因此您必须处理DOMAttrModified文档根元素上的所有事件确保捕获所有内容。
您可以使用attrchange jQuery插件。插件的主要功能是在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 == "display") { // which attribute you want to watch for changes
if(evnt.newValue.search(/inline/i) == -1) {
// your code to execute goes here...
}
}
}
});
对于CSS过渡将影响的属性,可以使用transitionend事件,例如z-index:
$(".observed-element").on("webkitTransitionEnd transitionend", function(e) {
console.log("end", e);
alert("z-index changed");
});
$(".changeButton").on("click", function() {
console.log("click");
document.querySelector(".observed-element").style.zIndex = (Math.random() * 1000) | 0;
});
.observed-element {
transition: z-index 1ms;
-webkit-transition: z-index 1ms;
}
div {
width: 100px;
height: 100px;
border: 1px solid;
position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="changeButton">change z-index</button>
<div class="observed-element"></div>
你不能 CSS不支持“事件”。敢问你需要什么?在SO上查看此帖子。我想不出您为什么要将事件挂接到样式更改的原因。我在这里假设样式更改是由其他javascript触发的。为什么不在那里添加额外的逻辑呢?