關於擷取、設定css樣式封裝的函數入門版

來源:互聯網
上載者:User

標籤:return   span   char   asc   style   根據id擷取   attr   head   測試   

 1 <html> 2     <head>   3         <meta charset="UTF-8">   4          <title>CSS樣式的擷取和設定:簡單版</title>   5         <style type="text/css">   6           #div {   7               width: 100px;   8               height: 100px;   9               background: pink;  10               }  11          </style>  12          <script type="text/javascript">  13              //根據id擷取元素  14              function $(id) {  15                  return document.getElementById(id);  16             }  17              //擷取樣式  18              function getStyle(obj, attr) {  19                  //哪個對象obj  20                  //哪個屬性attr  21                  //相容IE  22                  if (obj.currentStyle) {  23                      return obj.currentStyle[attr];  24                  }   25                  else { 26                      //相容Google Firefox   27                      return getComputedStyle(obj, false)[attr];  28                  }  29              }  30              31              //擷取或者設定CSS的屬性 32              function css(obj, attr, value) {  33                  //擷取CSS的數值  34                  if (arguments.length == 2) {  35                     return getStyle(obj, attr);  36                  }  37                  //設定CSS的數值  38                  if (arguments.length == 3) {  39                     obj.style[attr] = value;  40                  }  41              }  42              //調用CSS()方法,進行測試  43              window.onload = function() {  44                  css($("div"), "width", “200px”);  45              }  46              // 最後可以把這寫在一起,一個函數就搞定47              function css(obj,attr,value){48                 var getStyle = obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj,false)[attr];49                 if(arguments.length === 2){50                     return getStyle;51 52                 }else if(arguments.length === 3){53                     obj.style[attr] = value;54                 }55             }56         </script>  57      </head>  58        <body>  59          <div id="div"></div>  60      </body>61 </html>  

 

關於擷取、設定css樣式封裝的函數入門版

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.