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

Ada*_*son 6 javascript css jquery

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

例如:

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.
Run Code Online (Sandbox Code Playgroud)

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

我的另一个尝试是使用jQuery的对象扩展方法来创建一个副本:

var curr_style = $.extend( {}, el.style );
Run Code Online (Sandbox Code Playgroud)

这似乎不起作用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;
};
Run Code Online (Sandbox Code Playgroud)

Ray*_*nos 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";
}
Run Code Online (Sandbox Code Playgroud)

style具有不可枚举的属性,这些属性会.extend导致翻倒.您希望使用该getComputedStyle方法来获取元素的样式.

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

第一个参数(设置为true)告诉jQuery进行深度克隆.


Tim*_*own 5

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

js小提琴:

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;
Run Code Online (Sandbox Code Playgroud)