Cloning Element Styles for Pseudo Cloning
Issue:
You want a jQuery plugin that emulates cloning element styles without restricting the element tag. For instance, you might want to create a form input that replicates the visual appearance of an existing span.
Solution:
A suitable plugin for this purpose is getStyleObject. This plugin retrieves all computed CSS styles for a given element, including those not explicitly set through inline styles.
Implementation:
<code class="javascript">/* * getStyleObject Plugin for jQuery JavaScript Library * From: http://upshots.org/?p=112 * * Copyright: Unknown, see source link * Plugin version by Dakota Schneider (http://hackthetruth.org) */ (function($){ $.fn.getStyleObject = function(){ var dom = this.get(0); var style; var returns = {}; if(window.getComputedStyle){ var camelize = function(a,b){ return b.toUpperCase(); } style = window.getComputedStyle(dom, null); for(var i=0;i<style.length;i++){ var prop = style[i]; var camel = prop.replace(/\-([a-z])/g, camelize); var val = style.getPropertyValue(prop); returns[camel] = val; } return returns; } if(dom.currentStyle){ style = dom.currentStyle; for(var prop in style){ returns[prop] = style[prop]; } return returns; } return this.css(); } })(jQuery);</code>
Usage:
To apply styles from one element to another, use the following syntax:
<code class="javascript">// original element var original = $("#original"); // cloned element without styling yet var cloned = original.clone().appendTo(original.parent()); // get styles from original element var style = original.getStyleObject(); // apply styles to cloned element cloned.css(style);</code>
The above is the detailed content of How to Clone Element Styles Without Tag Restrictions. For more information, please follow other related articles on the PHP Chinese website!