如何使用JavaScript或jQuery克隆HTML元素的样式对象?

时间:2011-06-02 09:30:31

标签: javascript jquery css

我正在尝试克隆元素的样式对象。这应该允许我在更改后重置所述元素的样式。

例如:

el.style.left;      // 50px
curr_style.left;    // 50px;

/* 
Modify the elements style.
The cloned style should still hold the original properties from when it was cloned.
*/
el.style.left = '20px';
curr_style.left // should still return 50px.

我首先尝试通过为el.style的值赋值来复制它。不幸的是,这通过引用指向它,并且对样式的任何更改都反映在克隆对象中。

我的其他尝试涉及使用jQuery的对象扩展方法来创建副本:

var curr_style = $.extend( {}, el.style );

这似乎不起作用curr_style.left等返回undefined。

任何帮助将不胜感激!

我最终这样做是为了检索每个属性:(根据@Raynos的建议)

$.fn.getStyle = function(){
    var style,
    el = this[0];

    // Fallbacks for old browsers.
    if (window.getComputedStyle) {
        style = window.getComputedStyle( el );
    } else if (el.currentStyle) {
        style = $.extend(true, {}, el.currentStyle);
    } else {
        style = $.extend(true, {}, el.style);
    }

    // Loop through styles and get each property. Add to object.
    var styles = {};
    for( var i=0; i<style.length; i++){
        styles[ style[i] ] = style[ style[i] ];
    }

    return styles;
};

2 个答案:

答案 0 :(得分:6)

var curr_style;
if (window.getComputedStyle) {
    curr_style = window.getComputedStyle(el);
} else if (el.currentStyle) {
    curr_style = $.extend(true, {}, el.currentStyle);
} else {
    throw "shit browser";
}

style具有不可枚举的属性,导致.extend失效。您想使用getComputedStyle方法来获取元素的样式。

您还希望通过扩展具有可枚举属性的el.currentStyle来支持旧版本的IE。

第一个参数(设置为true时)告诉jQuery执行深度克隆。

答案 1 :(得分:4)

为了简单地重置样式,我建议您只使用style对象的cssText(另请参阅MDN)属性。这适用于所有主流浏览器,非常简单。

的jsfiddle:

http://jsfiddle.net/timdown/WpHme/

示例代码:

// Store the original style
var originalCssText = el.style.cssText;

// Change a style property of the element
el.style.fontWeight = "bold";

// Now reset
el.style.cssText = originalCssText;
相关问题