【フロントエンド学習】JavaScript閉パッケージhtml要素計算後のスタイルを取得


文書ディレクトリ
  • ・関数外部環境閉包影響
  • ・異なるバージョンのブラウザはhtml要素の計算後のスタイル
  • を取得する
    ・関数外部環境閉包の影響
    iの定義はfunctionの外部にあるため,閉パケットの影響を受けるため,thisキーワードを用いてイベントのオブジェクトをトリガする必要がある.jの定義はfunction内部にあるので,閉パケットの影響を受けない.
    for(var i = 0 ; i < pa1.length ; i ++) {
    			//    i   index   
    			pa1[i].index = i;
    			//     
    			pa1[i].onclick = function() {
    				for(var j = 0 ;j < pa2.length; j ++) {
    					pa2[j].style.backgroundColor = "blue";
    				}
    				pa2[this.index].style.backgroundColor = "red";
    			};
    		}
    

    ・異なるバージョンのブラウザがhtml要素の計算後のスタイルを取得する
    	
    1
    var oBox = document.getElementById("box"); console.log(oBox.style.width);

    styleでは行内スタイルのみを読み取れ、CSS計算後のスタイルは読み取れません.
  • Explorer getComputedStyle()、getPropertyValue()を使用して、計算後のスタイルの単一プロパティを取得します.短横border-width
  • window.getComputedStyle(oBox).getPropertyValue("width");
    
    window.getComputedStyle(oBox)["border-width"];
    
  • IE 6,7,8計算後のスタイルの単一属性をcurrentStyleで取得:アルパカborderWidth
  • oBox.innerHTML = oBox.currentStyle.width;
    
    oBox.innerHTML = oPic.currentStyle["borderColor"];
    
  • は、関数を使用して高度なブラウザまたは低レベルのブラウザを自動的に識別し、ユーザー入力が取得したい属性を自動的に短横またはアルパカの形に変換することと互換性がある.
  • 	<script type="text/javascript">
    		//       
    		var oBox = document.getElementById("box");
    		var oPic = document.getElementById("pic");
    		//  img      
    		// oBox.innerHTML = getValue("borderWidth",oPic);
    		oBox.innerHTML = getValue("border-width",oPic);
    
    		//      border-width,borderWidth
    		//    
    		function getValue(property, obj) {
    			if(window.getComputedStyle) {
    				//   
    				//           borderWidth  border-width
    				property = property.replace(/([A-Z])/g,function(match,$1) {
    					return "-" + $1.toLowerCase();
    				});
    				//       
    				return window.getComputedStyle(obj)[property];
    			}else {
    				// IE border-width  borderWidth
    				property = property.replace(/-([a-z])/g,function(match,$1) {
    					return $1.toUpperCase();
    				});
    				//       
    				return obj.currentStyle[property];
    			}
    		}		
    	</script>