JS による CSS スタイルの取得 (style/getComputedStyle/currentStyle)_javascript スキル

WBOY
リリース: 2016-05-16 15:19:19
オリジナル
1214 人が閲覧しました

CSS スタイルは 3 つのカテゴリに分類されます:
インライン スタイル: はタグ内に記述され、インライン スタイルはすべてのタグに対してのみ有効です。
内部スタイル: は HTML で記述され、内部スタイルはそれが配置されている Web ページでのみ有効です。
外部スタイル シート: 多くの Web ページで同じスタイル (スタイル) を使用する必要がある場合は、.css 接尾辞が付いた CSS ファイルにスタイル (スタイル) を記述して追加します。これらのスタイル (スタイル) を使用する必要がある Web ページでこの CSS ファイルを参照します。

getComputedStyle は、現在の要素の最終的に使用される CSS プロパティ値をすべて取得できるメソッドです。返されるのは CSS スタイル オブジェクト ([object CSSStyleDeclaration])
currentStyle は IE ブラウザのプロパティであり、CSS スタイル オブジェクト

を返します。

要素は、JS
によって取得された DOM オブジェクトを参照します element.style //埋め込みスタイルのみを取得できます
element.currentStyle //IE ブラウザは非埋め込みスタイルを取得します
window.getComputedStyle(element, pseudo-class) //非 IE ブラウザは非埋め込みスタイルを取得します
document.defaultView.getComputedStyle(element, pseudo-class)//非 IE ブラウザは非埋め込みスタイルを取得します
注: Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) より前では、2 番目のパラメーター「擬似クラス」が必須でした (擬似クラスでない場合は、null に設定します)。このパラメーターは現在、省略。

次の HTML には 2 つの CSS スタイルが含まれています。id タグを持つ div はインライン スタイルであり、id テストを持つ div は内部スタイルです。

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="Generator" content="EditPlus&reg;">
    <meta name="Author" content="Yvette Lau">
    <meta name="Keywords" content="关键字">
    <meta name="Description" content="描述">
    <title>Document</title>
    <style>
      #test{
        width:500px;
        height:300px;
        background-color:#CCC;
        float:left;
      }
    </style>
  </head>
  <body>
    <div id = "test"></div>
    <div id = "tag" style = "width:500px; height:300px;background-color:pink;"></div>
  </body>
</html>
ログイン後にコピー

JS パート

<script type = "text/javascript">
  window.onload = function(){
    var test = document.getElementById("test");
    var tag = document.getElementById("tag");

    //CSS样式对象:CSS2Properties{},CSSStyleDeclaration
    console.log(test.style); //火狐返回空对象CSS2Properties{},谷歌返回空对象CSSStyleDeclaration{} 
    console.log(tag.style); //返回CSS2Properties{width:"500px",height:"300px",background-color:"pink"}
    //element.style获取的是内嵌式的style,如果不是内嵌式,则是一个空对象

    console.log(tag.style.backgroundColor);//pink
    console.log(tag.style['background-color']);//pink
    //获取类似background-color,border-radius,padding-left类似样式的两种写法啊

    console.log(test.currentStyle) //火狐和谷歌为Undefined,IE返回CSS对象
    console.log(window.getComputedStyle(test,null))//谷歌返回CSSStyleDeclaration{……} ,火狐返回CSS2Properties{……}
    console.log(window.getComputedStyle(test))
    //效果同上,但是在Gecko 2.0 (Firefox 4/Thunderbird 3.3/SeaMonkey 2.1) 之前,第二个参数“伪类”是必需的(如果不是伪类,设置为null)

    console.log(test.currentStyle.width);//500px(IE)
    console.log(window.getComputedStyle(test).width); //500px;
    console.log(window.getComputedStyle(test)['width']);//500px;
    //document.defaultView.getComputedStyle(element,null)[attr]/window.getComputedStyle(element,null)[attr]   
  }
</script>

ログイン後にコピー

上記の例は、前の議論が正しいかどうかを確認するためだけのものです。

簡単にするために、取得スタイルの単純なカプセル化を作成することもできます。

function getStyle(element, attr){
      if(element.currentStyle){
        return element.currentStyle[attr];
      }else{
        return window.getComputedStyle(element,null)[attr];
      }
    }
    console.log(getStyle(test,"cssFloat"));//left
    console.log(getStyle(test,"float"));  //left,早前FF和chrome需要使用cssFloat,不过现在已经不必
    console.log(getStyle(test,"stylefloat"));//火狐和谷歌都是undefined
    console.log(getStyle(test,"styleFloat")); //IE9以下必须使用styleFloat,IE9及以上,支持styleFloat和cssFloat

    console.log(window.getComputedStyle(test).getPropertyValue("float"))

ログイン後にコピー

float スタイルに対応して、IE は styleFloat を使用し、以前の FF と chrome は cssFloat を使用しました。現在 FF と Chrome は既に float をサポートしています。また、その他の属性もいくつかあります。これらの違いを覚えておいてください。CSS スタイル オブジェクトにアクセスする 2 つの方法を紹介します。
getPropertyValue メソッドと getAttribute メソッド

IE9 およびその他のブラウザ (getPropertyValue)
window.getComputedStyle(element, null).getPropertyValue(“float”); element.currentStyle.getPropertyValue(“float”); getPropertyValue はキャメルケース表記をサポートしていません。 (IE9以降、FF、Chrom、Safari、Operaと互換性があります)
例: window.getComputedStyle(element,null).getPropertyValue(“background-color”);

IE6~8 の場合、getAttribute メソッドを使用して CSS スタイル オブジェクトの属性にアクセスする必要があります

element.currentStyle.getAttribute("float");//styleFloat として記述する必要がなくなりました

element.currentStyle.getAttribute("backgroundColor");//属性名はキャメルケースで記述する必要があります。そうでない場合、IE6 はサポートしません。IE6 を無視する場合は、「background-color」と記述できます。


以上がこの記事の全内容であり、皆さんの学習に役立ち、JS を使用して CSS スタイルを簡単に取得できることを願っています。

関連ラベル:
ソース:php.cn
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!