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

时间:2013-07-17 20:36:38

标签: javascript jquery dynamic

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

4 个答案:

答案 0 :(得分:3)

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

请参阅:MutationObserverMutation 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

答案 1 :(得分:2)

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

DEMO: 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/

答案 2 :(得分:0)

我认为您需要为JQuery使用插件,例如Ben Alman's plugin

我不认为有什么东西会检测div何时调整大小,只有窗口。

答案 3 :(得分:0)

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