Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何克隆HTML元素';使用JavaScript或jQuery的s样式对象?_Javascript_Jquery_Css - Fatal编程技术网

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

如何克隆HTML元素';使用JavaScript或jQuery的s样式对象?,javascript,jquery,css,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.

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

例如:

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的object extend方法创建副本:

var curr_style = $.extend( {}, el.style );
这似乎不适用于curr_style.left等。返回未定义

任何帮助都将不胜感激

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

$.fn.getStyle=function(){
var风格,
el=这个[0];
//旧浏览器的回退。
if(window.getComputedStyle){
style=window.getComputedStyle(el);
}else if(el.currentStyle){
style=$.extend(true,{},el.currentStyle);
}否则{
style=$.extend(true,{},el.style);
}
//循环浏览样式并获取每个属性。添加到对象。
var样式={};
对于(var i=0;i
style
具有不可枚举的属性,这会使
.extend
失效。您希望使用
getComputedStyle
方法获取元素的样式

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


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

为了简单地重置样式,我建议只使用
style
对象的(另请参见)属性。这在所有主要浏览器中都有效,而且非常简单

jsFiddle:

示例代码:

// 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;

您好,这似乎是朝着正确的方向迈出的一步。我遇到的问题是,style对象似乎不是一个基本的javascript对象。例如,在firebug中检查style对象和克隆对象,它们似乎具有相同的属性。它们都没有“left”属性,但是style.left将返回一个值curr_style.left不会。@AdamHutchinson问题是
style
的属性是不可枚举的。@Raynos有什么办法可以绕过它吗?@AdamHutchinson是的。使用
computedStyle
currentStyle
这些属性具有可枚举的属性。(computedStyle还返回一个新对象,因此很酷)@Raynos似乎更改el.style.left会导致curr_style.left返回的值发生更改,即使在使用ComputedStyle时也是如此。Hi Tim,我计划使用jQuery的动画方法执行重置,并且只使用style对象的某些属性。@Adam:很公平,我的答案不行。无论如何,我都会把它留给任何人将来遇到这个问题,它可能会帮助谁。
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";
}
// 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;