jQuery给多个不同元素添加class样式的方法
jQuery可以通过addClass()方法给多个不同的html元素同时添加相同的class
<!DOCTYPE html>
<html>
<head>
<script src="js/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>
jquery中怎样根据父级找元素
jquery中parent()可以获取父级元素,所以获得某元素父级的父级可以使用
$(selector).parent().parent();
示例如下
创建Html代码及css样式
class1
class2
class3
div{padding:10px 20px;border:4px solid #ebcbbe;}
div.class1{width:200px;height:120px;}
编写jquery代码
$(function(){
$("div.class3").click(function() {
obj = $(this).parent().parent();
alert(obj.prop('class'));
});
})
如何利用jquery来向一个元素中添加和移除css类
Jquery使用addClass()与removeClass()来动态的添加或移出一个css类,例如:
1.$(“#para1”).addClass('highlight');添加一个“highlight”css类给id为para1的元素。
2.$(‘#para1’).removeClass(‘'highlight');从id为para1的元素中移出一个‘highlight’css类。具体实例代码如下:<html><head><styletype="text/css">.highlight{background:green;}</style><scripttype="text/javascript"src="jquery-1.
3.2.min.js"></script></head><body><h1>jQueryadd/removecssclassexample</h1><pid="para1">Thisisparagraph1</p><p>Thisisparagraph2</p><p>Thisisparagraph3</p><p>Thisisparagraph4</p><buttonid="addClass">Addhighlight</button><buttonid="removeClass">Removehighlight</button><scripttype="text/javascript">$("#addClass").click(function(){$('#para1').addClass('highlight');});$("#removeClass").click(function(){$('#para1').removeClass('highlight');});</script></body></html>初始的效果:点击addhighlight后的效果图:点击removehighlight后的效果图:
发表评论