JavaScript が CSS スタイルを取得する
構文:
nodeObject.style.cssProperty
このうち、nodeObjectはノードオブジェクト、cssPropertyはCSSプロパティです。
例:
document.getElementById("demo").style.height;
document.getElementById("demo").style.border;注: 「-」で区切られた CSS プロパティの場合は、「-」を削除し、「-」の後の最初の文字を大文字にします。例:
background-color は、backgroundColor として記述する必要があります
line-height は、lineHeight として記述する必要があります
例:
document.getElementById("demo").style. backgroundColor;
document.getElementById("demo").style.lineHeight;たとえば、id="demo" でノードのスタイルを取得します:
<div id="demo" style="height:50px; width:250px; margin-top:10px; text-align:center; line-height:50px; background-color:#ccc;">
点击这里获取CSS样式
</div>
<script type="text/javascript">
document.getElementById("demo").onclick=function(){
alert(
"高度:"+this.style.height+"\n"+
"宽度:"+this.style.width+"\n"+
"上边距:"+this.style.marginTop+"\n"+
"对齐:"+this.style.textAlign+"\n"+
"行高:"+this.style.lineHeight+"\n"+
"背景颜色:"+this.style.backgroundColor
);
}
</script>Slightly上記のコードを修正し、CSS スタイルを変更します。 HTML から分離します:
<style>
#demo{
height:50px;
width:250px;
margin-top:10px;
text-align:center;
line-height:50px;
background-color:#ccc;
}
</style>
<div id="demo">
点击这里获取CSS样式
</div>
<script type="text/javascript">
document.getElementById("demo").onclick=function(){
alert(
"高度:"+this.style.height+"\n"+
"宽度:"+this.style.width+"\n"+
"上边距:"+this.style.marginTop+"\n"+
"对齐:"+this.style.textAlign+"\n"+
"行高:"+this.style.lineHeight+"\n"+
"背景颜色:"+this.style.backgroundColor
);
}
</script> CSS スタイルを HTML コードから分離すると、CSS スタイルを取得できないことがわかります。これは、nodeObject.style.cssProperty
は、DOMノードのstyle属性で定義されたスタイルを取得するため、style属性が存在しないか、style属性に対応するスタイルが定義されていない場合は取得できません。
言い換えると、JavaScript は対応するスタイルを取得するために <style> タグや CSS ファイルにアクセスすることはなく、style 属性で定義されたスタイルのみを取得できます。
新しいファイル
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<div id="demo" style="height:50px; width:250px; margin-top:10px; text-align:center; line-height:50px; background-color:#ccc;">
点击这里获取CSS样式
</div>
<script type="text/javascript">
document.getElementById("demo").onclick=function(){
alert(
"高度:"+this.style.height+"\n"+
"宽度:"+this.style.width+"\n"+
"上边距:"+this.style.marginTop+"\n"+
"对齐:"+this.style.textAlign+"\n"+
"行高:"+this.style.lineHeight+"\n"+
"背景颜色:"+this.style.backgroundColor
);
}
</script>
</head>
<body>
</body>
</html>
プレビュー
Clear
- おすすめコース
- コースウェアのダウンロード
現時点ではコースウェアはダウンロードできません。現在スタッフが整理中です。今後もこのコースにもっと注目してください〜
このコースを視聴した生徒はこちらも学んでいます
















