如何使用JavaScript或jQuery克隆HTML元素的样式对象? [英] How do I clone an HTML element's style object using JavaScript or jQuery?
问题描述
我正在尝试克隆元素的样式对象。这应该允许我在更改后重置所述元素的样式。
I'm trying to clone the style object of an element. This should allow me to reset the styles of said element after I change them.
例如:
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的值赋值来复制它。不幸的是,这通过引用指向它,并且对样式的任何更改都反映在克隆对象中。
I first tried to copy it by assigning a variable to the value of el.style. Unfortunately, this points to it by reference and any changes to the style are reflected in the cloned object.
我的其他尝试涉及使用jQuery的对象扩展方法来创建副本:
My other attempt involved using jQuery's object extend method to create a copy as such:
var curr_style = $.extend( {}, el.style );
这似乎不起作用curr_style.left等返回undefined。
This doesn't seem to work as curr_style.left etc. return undefined.
任何帮助都将不胜感激!
Any help would be appreciated!
我最终这样做是为了检索每个属性:(基于根据@Raynos的建议)
I ended up doing this to retrieve each property: (based on advice from @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
有非-enumerable属性使 .extend
失效。您想使用 getComputedStyle
方法来获取元素的样式。
style
has non-enumerable properties which makes .extend
fall over. You want to use the getComputedStyle
method to get the styles of an element.
您还希望支持旧版本通过扩展 el.currentStyle
来确保IE具有可枚举属性。
You also want to support older versions of IE by extending el.currentStyle
which does have enumerable properties.
第一个参数(设置为<$时) c $ c> true )告诉jQuery执行深克隆。
The first argument (when set to true
) tells jQuery to do a deep clone.
这篇关于如何使用JavaScript或jQuery克隆HTML元素的样式对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!