我知道如何在窗口大小更改时使用 Jquery 更改类,但我需要它基于 DIV 的宽度,并在 DIV 宽度更改时动态更改。
$(window).resize(function() {
var wrapWidth = $('.info-wrap').width();
if (wrapWidth >= 500) {
$('#partOne').addClass('big');
$('#partTwo').addClass('big');
} else {
$('#partOne').removeClass('big');
$('#partTwo').removeClass('big');
}
});
这在窗口大小改变时起作用。但是,我可以使用什么来代替 $(window).resize 来获取 DIV 变化时的宽度?
最佳答案
这是观察元素属性的示例。
参见:MutationObserver
和 Mutation Events
CSS
#watch {
border: 1px solid;
}
HTML
<button id="button">Click me</button>
<div id="watch" style="width: 100px; height: 50px;"></div>
Javascript
/*jslint sub: true, maxerr: 50, indent: 4, browser: true */
/* global global */
(function (global) {
"use strict";
if (typeof global.MutationObserver !== "function") {
global.MutationObserver = global.WebKitMutationObserver || global.MozMutationObserver;
}
var watch = document.getElementById("watch");
function whenClicked() {
watch.style.width = "200px";
}
document.getElementById("button").addEventListener("click", whenClicked, false);
if (typeof global.MutationObserver !== "function") {
// chrome doesn't despatch an event for "DOMAttrModified"
watch.addEventListener("DOMAttrModified", function (evt) {
console.log("Attribute changed", evt.target);
}, false);
} else {
var observer = new global.MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
if (mutation.type === 'attributes') {
console.log("Attribute changed", mutation);
}
});
});
observer.observe(watch, {
attributes: true,
childList: true,
characterData: true,
subtree: true
});
}
}(window));
关于 jsfiddle
关于javascript - 如何在DIV宽度改变时动态改变类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17709726/