JQuery样式操作、click事件以及索引值-选项卡应用示例
本文实例讲述了JQuery样式操作、click事件以及索引值-选项卡应用。分享给大家供大家参考,具体如下:
JQuery的css函数既能读属性值,也能写属性值:
样式操作
$(function(){
var$div=$('#box');
varsTr=$div.css('fontSize');//读
alert(sTr);
$div.css({backgroundColor:'pink',color:'black',fontSize:'20px'})//写
});
div元素
其实不光是css函数,JQuery内的其他函数也是这样的,如果放值就是写,如果不放就是读。
样式的加减
Title
$(function(){
var$div=$('.box');
$div.addClass('big');//加入big类
$div.removeClass('red');//去除red样式类
})
.box{
width:100px;
height:100px;
background-color:red;
}
.big{
font-size:30px;
}
.red{
color:green;
}
div元素
给元素绑定click事件
$('#btn1').click(function)(){
//内部的this指的是原生对象
//使用JQuery对象用$(this)
}
点击事件,切换样式
Title
$(function(){
var$btn=$('#btn');
$btn.click(function(){//绑定事件
//var$div=$('.box');
//if(!$div.hasClass('col01')){
//alert(1);
//}
//$div.addClass('col01');
//可以简化成下面的写法
$('.box').toggleClass('col01');//切换样式
})
});
.box{
width:200px;
height:200px;
background-color:gold;
}
.col01{
background-color:green;
}
div元素
索引值-选项卡
有时候需要获得匹配元素相对于其同胞元素的索引位置,此时可以用index()方法获取。
var$li=$('.listli').eq();
alert($li.index());//弹出
1
2
..............
6
得到索引值
Title
$(function(){
var$li=$('.listli');
//alert($li.length);
alert($li.eq(3).index());
vars=$li.filter(".myli").index();
alert(s);
})
1
2
3
4
5
6
7
8
选项卡的制作,点击事件之后,当前点击的事件加上样式,其他统计的元素,去掉样式,关键代码
$(this).addClass('current').siblings().removeClass('current');
varnum=$(this).index();
$div.eq($(this).index()).addClass('active').sibling().removeClass('active');
完整:
Title
.btnsinput{
width:100px;
height:40px;
background-color:grey;
border:0;
}
.btns.current{
background-color:gold;
}
.consdiv{
width:500px;
height:300px;
background-color:gold;
display:none;/*整体都不显示了*/
text-align:center;
line-height:300px;
font-size:30px;
}
.cons.active{
display:block;
}
$(function(){
var$btn=$('.btnsinput');
var$div=$('.consdiv');
//alert($btn.length);
//alert($div.length);
$btn.click(function(){
//我点击哪一个按钮,$(this)就指的是谁,而this
//指的是原生的,$(this)指的是JQuery的
//$(this).siblings().removeClass('current');
//$(this).addClass('current');//可以用链式调用
$(this).addClass('current').siblings().removeClass('current');
varnum=$(this).index();
$div.eq($(this).index()).addClass('active').sibling().removeClass('active');
})
})