如何克隆HTML元素's风格的对象使用JavaScript或jQuery

How do I clone an HTML element's style object using JavaScript or jQuery?

本文关键字:对象 JavaScript jQuery 风格 HTML 何克隆 元素      更新时间:2023-09-26

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

例如:

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;
};
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";
}

CCD_ 1具有不可枚举的属性,这使得CCD_。您希望使用getComputedStyle方法来获取元素的样式。

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

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

为了简单地重置样式,我建议只使用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;