通过jQuery可以操作控制元素的样式,文本,属性等
jquery样式操作
css操作行内样式
// 获取div的样式
$("div").css("width");
$("div").css("color");
//设置div的样式
$("div").css("width","30px");
$("div").css("height","30px");
$("div").css({fontSize:"30px",color:"red"});
特别注意 选择器获取的多个元素,获取信息获取的是第一个,比如:$("div").css("width"),获取的是第一个div的width。
类名class操作
操作样式类名
$("#div1").addClass("divClass2") //为id为div1的对象追加样式divClass2
$("#div1").removeClass("divClass") //移除id为div1的对象的class名为divClass的样式
$("#div1").removeClass("divClass divClass2") //移除多个样式
$("#div1").toggleClass("anotherClass") //重复切换anotherClass样式,该方法检查每个元素中指定的类。如果不存在则添加类,如果已设置则删除之。这就是所谓的切换效果。
文本操作
1、html() 取出或设置html内容
// 取出html内容
var $htm = $('#div1').html();
// 设置html内容
$('#div1').html('<span>添加文字</span>');
2、text() 取出或设置text内容
// 取出文本内容
var htm = $('#div1').text();
// 设置文本内容
$('#div1').text('<span>添加文字</span>');
属性操作
1、attr() 取出或设置某个属性的值
// 取出图片的地址
var $src = $('#img1').attr('src');
// 设置图片的地址和alt属性
$('#img1').attr({ src: "test.jpg", alt: "Test Image" });
//也可以用户设置class属性
$('#abc').attr('class','all')
//也可以自定义 属性
$('#abc').attr('love','iloveyou')
2、removeAttr()删除属性
$('#abc').removeAttr('class');
$('#abc').removeAttr('love');
$("img").removeAttr("name src");
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>选项卡</title>
<script src="./jquery-1.8.3.js"></script>
<style>
*{margin:0;padding:0;list-style: none}
.wrap{
width:300px;
height:400px;
border:1px solid red;
margin:0 auto;
}
.title{
height:50px;
}
.title li{
width:100px;
height:50px;
border:1px solid red;
float:left;
box-sizing:border-box;
border-top:none;
border-left:none;
text-align:center;
line-height: 50px;
}
.title li:last-child{
border-right:none;
}
.title .item{
border-bottom:none;
}
.content li{
width:100%;
height:350px;
/*border:1px solid green;*/
text-align:center;
line-height:350px;
display:none;
}
.content .active{
display:block;
}
</style>
</head>
<body>
<div class="wrap">
<ul class="title">
<li class="item">标题一</li>
<li >标题二</li>
<li >标题三</li>
</ul>
<ul class="content">
<li class="active">内容一</li>
<li>内容二</li>
<li>内容三</li>
</ul>
</div>
<script>
// 给标题添加绑定事件
$('.title li').click(function(){
// console.log($(this));
// $(this).addClass('item');
// $(this).siblings().removeClass('item');
$(this).addClass('item').siblings().removeClass('item');
// 获取索引值 通过索引值将标题和内容关联起来
var index=$(this).index();
$('.content li').eq(index).addClass('active');
$('.content li').eq(index).siblings().removeClass('active');
})
</script>
</body>
</html>