2012-03-04 98 views
0

我已經嘗試過「window.getComputedStyle」和「currentStyle」,但它不能工作,除了鉻。 請首先看下我的演示,謝謝。 http://www.learning.fancyboy.net/javascript/cloneStyles.html 的代碼是:如何只將元素的樣式複製到另一個元素?

<!DOCTYPE html> 
<html> 
    <head> 
     <meta charset="utf-8" /> 
     <title>clone style</title> 
     <style> 
      *{margin:0;padding:0;} 
      #text1{width:200px;height:50px;border:1px solid red;color:#ccc;line-height:50px;padding:5px;margin:5px;} 
     </style> 
    </head> 

    <body> 
     <div> 
      <input type="text" id="text1" value="origin" /> 
      <input type="text" id="text2" value="clone" /> 
     </div> 
     <script> 
      var 
      text1=document.getElementById("text1"), 
      text2=document.getElementById("text2"), 
      cssObj, 
      sCssText=""; 
      if(!!window.getComputedStyle){ 
       cssObj=window.getComputedStyle(text1,null); 
       sCssText=cssObj.cssText; 
      } 
      else{ 
       cssObj=text1.currentStyle; 
       for(var k in cssObj){ 
        sCssText+=k+":"+cssObj[k]+";"; 
       } 
      } 
      text2.style.cssText=sCssText; 
     </script> 
    </body> 
</html> 

任何想法?

+0

http://www.quirksmode.org/dom/getstyles.html – Joseph 2012-03-04 06:18:14

回答

2

如果可能的話我會嘗試做這樣的事情:

<style> 
    *{margin:0;padding:0;} 
    .textclass{width:200px;height:50px;border:1px solid red;color:#ccc;line-height:50px;padding:5px;margin:5px;} 
</style> 

<input type="text" id="text1" value="origin" class="textclass" /> 
<input type="text" id="text2" value="clone" class="textclass" /> 

如果這不是一個可能性,那麼你可以使用這個jQuery函數(從http://upshots.org/javascript/jquery-copy-style-copycss):

$.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, l = style.length; i < l; i++){ 
      var prop = style[i]; 
      var camel = prop.replace(/\-([a-z])/g, camelize); 
      var val = style.getPropertyValue(prop); 
      returns[camel] = val; 
     }; 
     return returns; 
    }; 
    if(style = dom.currentStyle){ 
     for(var prop in style){ 
      returns[prop] = style[prop]; 
     }; 
     return returns; 
    }; 
    if(style = dom.style){ 
     for(var prop in style){ 
     if(typeof style[prop] != 'function'){ 
      returns[prop] = style[prop]; 
     }; 
     }; 
     return returns; 
    }; 
    return returns; 
} 

而(@source的所有樣式都傳遞給調用者):

$.fn.copyCSS = function(source){ 
    var styles = $(source).getStyleObject(); 
    this.css(styles); 
} 

// usage... 
// $('#my-element').copyCSS('#another-element'); 
// or... 
// $('#my-element').copyCSS(someReferenceToAnElement); 
+0

謝謝!它在大多數瀏覽器中都能正常工作,除非opera,但它解決了我的特定問題。 – fancy 2012-03-04 07:36:33

相關問題