繁体   English   中英

如何使用 JavaScript 或 ZF590B4FDA2C30BE28DD3C8C3CAF5C7 克隆 HTML 元素的样式 object?

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

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

例如:

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 的值来复制它。 不幸的是,这通过引用指向它,并且样式的任何更改都反映在克隆的 object 中。

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

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

这似乎不起作用,因为 curr_style.left 等返回未定义。

任何帮助,将不胜感激!

我最终这样做是为了检索每个属性:(基于@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";
}

style具有不可枚举的属性,这使得.extend失败。 您想使用getComputedStyle方法获取元素的 styles。

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

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

为了简单地重置 styles,我建议只使用 object stylecssText (另见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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM