class属性在html,HTML Class属性用法及代码示例

html中的类:

类别是为HTML元素指定一个或多个类别名称的属性。

class属性可以在任何HTML元素上使用。

CSS和JavaScript可以使用该类名来为具有指定类名的元素执行某些任务。

例:

.country {

background-color:black;

color:white;

padding:8px;

}

CHINA

China has the largest population

in the world.

INDIA

India has the second largest

population in the world.

UNITED STATES

United States has the third largest

population in the world.

输出:

abcf8d8f4a8aae4188d3bbf488933cb4.png

说明:在以上示例中,CSS用类名“country”设置了所有元素的样式。

在JavaScript中使用class属性:JavaScript可以使用getElementsByClassName()方法访问具有指定类名称的元素。

例:

function myFunction() {

var x = document.getElementsByClassName("country");

for (var i = 0; i < x.length; i++) {

x[i].style.display = "none";

}

}

Click the button, and a JavaScript hides all

elements with the class name "country":

Hide elements

CHINA

China has the largest population in the world.

INDIA

India has the second largest population in the world.

UNITED STATES

United States has the third largest population

in the world.

输出:

在单击“隐藏元素”按钮之前:

e0bac98c25bb256e1a22277df981ba5e.png

单击“隐藏元素”按钮后:

4fb800fef6e99f8d2685d554486507a1.png

使用多个类:

HTML元素可以具有多个类名,其中每个类名必须用空格分隔。

例:

.country {

background-color:black;

color:white;

padding:10px;

}

.middle {

text-align:center;

}

CHINA

INDIA

UNITED STATES

输出:

14b2c10b28cd75a09fe899fca986dff6.png

说明:所有三个头均具有类名“country”,但除此之外,CHINA也具有类名“middle”,这使得文本为center-aligned。

在不同的标记中使用相同的类:不同的标记(例如

)可以具有相同的类名,从而共享相同的样式。

例:

.country {

background-color:black;

color:white;

padding:10px;

}

CHINA

China has the largest

population in the world.

输出:

d460fa01a03f08539e745d3da2059da5.png

说明:即使两个元素没有相同的标签名,它们也可以具有相同的类名,并具有相同的样式。

支持的浏览器:下面列出了Class属性支持的浏览器:

谷歌浏览器

IE浏览器

Firefox

Opera

Safari

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值