文章目录[隐藏]
我们通过jQuery非常方便容易的对CSS进行类的添加,删除,切换,极为方便的获取并设置css的类,下面我们一起看几个Demo.
jQuery 操作 CSS
jQuery 拥有若干进行 CSS 操作的方法。我们将学习下面这些:
- ○ addClass() - 向被选元素添加一个或多个类
- ○ removeClass() - 从被选元素删除一个或多个类
- ○ toggleClass() - 对被选元素进行添加/删除类的切换操作
- ○ css() - 设置或返回样式属性
以下所有Demo用到的样式表
.important{font-weight:bold;
font-size:xx-large;
}.blue{color:blue;
}
jQuery addClass() 方法
下面的例子展示如何向不同的元素添加 class 属性。当然,在添加类时,您也可以选取多个元素:
$("button").click(function(){
$("h1,h2,p").addClass("blue");
$("div").addClass("important");
});
实例:
<!DOCTYPE html><html><head><script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script><script>$(document).ready(function(){
$("button").click(function(){
$("h1,h2,p").addClass("blue");
$("div").addClass("important");
});
});
</script><style type="text/css">
.important{font-weight:bold;
font-size:xx-large;
}.blue{color:blue;
}</style></head><body><h1>Heading 1</h1>
<h2>Heading 2</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<div>This is some important text!</div>
<br><button>Add classes to elements</button>
</body></html>
您也可以在 addClass() 方法中规定多个类:
$("button").click(function(){
$("#div1").addClass("important blue");
});
实例:
<!DOCTYPE html><html><head><script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script><script>$(document).ready(function(){
$("button").click(function(){
$("#div1").addClass("important blue");
});
});
</script><style type="text/css">
.important{font-weight:bold;
font-size:xx-large;
}.blue{color:blue;
}</style></head><body><div id="div1">This is some text.</div>
<div id="div2">This is some text.</div>
<br><button>Add classes to first div element</button>
</body></html>
jQuery removeClass() 方法
下面的例子演示如何在不同的元素中删除指定的 class 属性:
$("button").click(function(){
$("h1,h2,p").removeClass("blue");
});
实例:
<!DOCTYPE html><html><head><script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script><script>$(document).ready(function(){
$("button").click(function(){
$("h1,h2,p").removeClass("blue");
});
});
</script><style type="text/css">
.important{font-weight:bold;
font-size:xx-large;
}.blue{color:blue;
}</style></head><body><h1 class="blue">Heading 1</h1>
<h2 class="blue">Heading 2</h2>
<p class="blue">This is a paragraph.</p>
<p>This is another paragraph.</p>
<br><button>Remove class from elements</button>
</body></html>
jQuery toggleClass() 方法
下面的例子将展示如何使用 jQuery toggleClass() 方法。该方法对被选元素进行添加/删除类的切换操作:
$("button").click(function(){
$("h1,h2,p").toggleClass("blue");
});
实例:
<!DOCTYPE html><html><head><script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script><script>$(document).ready(function(){
$("button").click(function(){
$("h1,h2,p").toggleClass("blue");
});
});
</script><style type="text/css">
.blue{color:blue;
}</style></head><body><h1>Heading 1</h1>
<h2>Heading 2</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Toggle class</button>
</body></html>
