HTML的<class>
属性的作用是为有着相同’<class>'
值的元素赋予相同的格式。以下是一段定义<class>
的代码。
<!doctype html>
<html>
<head>
<style>
.cities{
color:white;
background-color:tomato;
text-align:left;
margin:20px;
padding:20px;
}
.main{
font-size:50%;
}
.Main{
font-size:150%;
}
</style>
</head>
<body>
<p class="cities">London</p>
<h2 class="cities"> Beijing</p>
<p class="cities main"> Tokoyo</p>
<p> This is <span class="main"> New York </span></p>
</body>
</html>
- 不同的标签都可以指向同一个 class name.
- 同一个标签可以同时指向多个class name
- Class name 是分大小写的。
- class name也可以被Javascript引用去实现特定功能。在学到Javascript的内容时可以再来看。其实是class name “city” 被"getElementsByClassName"方法引用,实现功能,当点击按钮时,可以隐藏所有带有“city"格式的元素。
<!DOCTYPE html>
<html>
<body>
<h2>Using The class Attribute in JavaScript</h2>
<p>Click the button, to hide all elements with the class name "city", with JavaScript:</p>
<button onclick="myFunction()">Hide elements</button>
<h2 class="city">London</h2>
<p>London is the capital of England.</p>
<h2 class="city">Paris</h2>
<p>Paris is the capital of France.</p>
<h2 class="city">Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>
<script>
function myFunction() {
var x = document.getElementsByClassName("city");
for (var i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
}
</script>
</body>
</html>