有没有办法在Javascript中拦截/监控CSS属性使用vanilla Javascript更改

时间:2011-07-20 17:12:40

标签: javascript css

有没有办法在Javascript中拦截/监控CSS属性使用vanilla Javascript更改?例如更改width属性:

.div {
    width:100px;
}

.div:hover {
   width:200px;
}

...

<div class="div">Blah</div>

编辑:我的意思是没有悬停状态更改,我希望检测到DIV的宽度属性已更改。它可能是任何其他属性或任何其他更改属性的方式:例如,我做div.className =“div bigBox”,其中:

.bigBox { width:200px;height:200px }

我想知道高度属性已经改变了!

3 个答案:

答案 0 :(得分:1)

您无法检测到类/宽度变化。

可以检测悬停。

document.getElementById('divID').onmouseover = function(event) {
    //do something
}

答案 1 :(得分:1)

您可以设置间隔并观察有问题的css属性:

var cssWatchInterval = false;
function cssWatch (element, property, handler) {
    if (cssWatchInterval !== false)
        clearInterval(cssWatchInterval);
    var comp = element.currentStyle || getComputedStyle(element, null);
    var current_prop_value = comp[property];
    cssWatchInterval = setInterval(function () {
        var comp = element.currentStyle || getComputedStyle(element, null);  
        if (comp[property] != current_prop_value) {
            stopCssWatch();
            handler(element);
        }
    }, 250);
};
function stopCssWatch() {
    clearInterval(cssWatchInterval);
}

在此处试试:http://jsfiddle.net/wAtvp/6/

答案 2 :(得分:1)

您可能希望查看jss 1.4.3 +中提供的cssHooks,而不是轮询

http://api.jquery.com/jQuery.cssHooks/