当前位置: 移动技术网 > IT编程>开发语言>JavaScript > jQuery HTML css()方法与css类实例详解

jQuery HTML css()方法与css类实例详解

2020年06月13日  | 移动技术网IT编程  | 我要评论

本文实例讲述了jquery html css()方法与css类。分享给大家供大家参考,具体如下:

jquery css() 方法

返回 css 属性

如需返回指定的 css 属性的值,请使用如下语法:

css("propertyname");

下面的例子将返回首个匹配元素的 background-color 值:

$("p").css("background-color");//只获取 了一个背景颜色

//获取多个
<body>
<h2>这是一个标题</h2>
<p style="background-color:#ff0000">这是一个段落。</p>
<p style="background-color:#00ff00">这是一个段落。</p>
<p style="background-color:#0000ff">这是一个段落。</p>
<button>返回第一个 p 元素的 background-color </button>
</body>

$("button").click(function(){
  alert("p1背景颜色 = " + $("p:nth-child(2)").css("background-color"));
  alert("p2背景颜色 = " + $("p:nth-child(3)").css("background-color"));
  alert("p3背景颜色 = " + $("p:nth-child(4)").css("background-color"));
});

nth-child() 选择器默认以 body 作为父标签,所以 :nth-child(1) 是 <h2> </h2>。

当页面的元素特别多,父子关系特别繁杂的时候,不可能一个个去数要的元素是 body 的第几个元素。

另一方面,页面可以动态的,body 下的索引容易变化,用这个方法指定某个元素非常不靠谱。

要选取第几个 p 的方法,正确的应该是这样:

$("p").eq(n) // n 是索引号,从 0 开始

设置 css 属性

如需设置指定的 css 属性,请使用如下语法:

css("propertyname","value");

下面的例子将为所有匹配元素设置 background-color 值:

$("p").css("background-color","yellow");

设置多个 css 属性

如需设置多个 css 属性,请使用如下语法:

css({"propertyname":"value","propertyname":"value",...});

下面的例子将为所有匹配元素设置 background-color 和 font-size:

$("p").css({"background-color":"yellow","font-size":"200%"});

获取并设置 css 类

jquery 操作 css

jquery 拥有若干进行 css 操作的方法。我们将学习下面这些:

  • addclass() - 向被选元素添加一个或多个类
  • removeclass() - 从被选元素删除一个或多个类
  • toggleclass() - 对被选元素进行添加/删除类的切换操作
  • css() - 设置或返回样式属性

实例样式表

下面的样式表将用于本页的所有例子:

.important { font-weight:bold; font-size:xx-large; } 
.blue { color:blue; }

addclass() 方法

下面的例子展示如何向不同的元素添加 class 属性。当然,在添加类时,也可以选取多个元素:

$("button").click(function(){
 $("h1,h2,p").addclass("blue");
 $("div").addclass("important");
});

也可以在 addclass() 方法中规定多个类:

$("button").click(function(){
 $("body div:first").addclass("important blue");
});

removeclass() 方法

下面的例子演示如何在不同的元素中删除指定的 class 属性:

$("button").click(function(){
 $("h1,h2,p").removeclass("blue");
});

toggleclass() 方法

下面的例子将展示如何使用 jquery toggleclass() 方法。该方法对被选元素进行添加/删除类的切换操作:

$("button").click(function(){
 $("h1,h2,p").toggleclass("blue");
});

感兴趣的朋友可以使用在线html/css/javascript代码运行工具:测试上述代码运行效果。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网