如何在DIV宽度变化时动态更改类?

我知道如何在更改窗口大小时使用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随其变化的宽度?

我认为你需要为JQuery使用一个插件,比如Ben Alman的插件 。

我不认为有什么东西可以检测div何时resize,只检测窗口。

以下是观察元素属性的示例。

请参阅: MutationObserverMutation Events

CSS

 #watch { border: 1px solid; } 

HTML

  

使用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

我曾经为attrchange监听器编写了一个插件,它基本上在属性更改时添加了一个监听器函数。 对于您提到需要处理程序来检查宽度和高度的情况,这似乎派上用场了。

演示: http //jsfiddle.net/CKTk3/1/

  var prevWidth = $('#test').width(), prevHeight = $('#test').height(); $('#test').attrchange({ callback: function (e) { var curWidth = $(this).width(), curHeight = $(this).height(); if (prevWidth !== curWidth || prevHeight !== curHeight) { console.log('resized: width - ' + prevWidth + ' : ' + curWidth + ' height - ' + prevHeight + ' : ' + curHeight); prevWidth = curWidth; prevHeight = curHeight; } } }).resizable(); 

插件页面: http //meetselva.github.io/attrchange/

您可以通过div类或id获得div宽度。 例如:$(“#div-id”)。width();