window.onload方法和$(document).ready()方法的区别
3种方式是等价的
$(document).ready(function(){ })
$(function(){ })
$().ready(function(){ })
事件绑定:bind() click mouseover mouseout 事件
流程:等待DOM转载完毕,找到标题所在的元素,绑定click事件,找到内容的元素,将内容元素显示出来。
$(function(){
$("#panel h5.header").bind("click",function(){
$(this).next().show(); $(this).next() 获取内容元素
})
})
为了判断元素是否存在,可以使用jQuery中的is()方法来完成。
$(function(){
$("#panel h5.header").bind("click",function(){
if($(this).next().is(":visible")){ //如果内容显示
$(this).next().hide(); $(this).next() 获取内容元素
}else{
$(this).next().show();
}
})
})
发现$(this).next()
被多次调用,因此可以为他定义一个局部变量
var $content=$(this).next();
然后把局部变量引入到代码中,改进后的jQuery代码如下:
$(function(){
$("#panel h5.header").bind("click",function(){
var $content=$(this).next();
if($content.is(":visible")){ //如果内容显示
$content.hide(); $(this).next() 获取内容元素
}else{
$content.show();
}
})
})
合成事件:hover()方法+toggle()方法,类似于前面讲过的ready()方法,都属于jQuery自定义的方法
$(function(){
$("#panel h5.head").hover(function(){
$(this).next().show();
}.function(){
$(this).next().hide();
})
})
实现一样的效果
$(function(){
$("#panel h5.head").toggle(function(){
$(this).next().show();
}.function(){
$(this).next().hide();
})
})
切换元素的可见状态,如果元素是可见的,单击切换后则为隐藏,如果元素是隐藏,点击切换后则为可见。
$(function(){
$("#panel h5.head").toggle(function(){
$(this).next().toggle();
}.function(){
$(this).next().toggle();
})
})
重点:
定义高亮的样式:.highlight{ background: $FF3300;}
1:等待DOM转载完毕
2:找到标题元素,添加toggle()方法,在toggle()方法里定义两个函数,分别表示显示或隐藏
3:在显示函数里,给标题添加高亮class
4:在隐藏函数里,移除标题的高亮class
$(function(){
$("#panel h5.head").toggle(function(){
$(this).addClass("hightlight"); //添加高亮样式
$(this).next().show();
}.function(){
$(this).removeClass("highlight"); //移除高亮样式
$(this).next().hide();
})
})
运行代码后,如果内容是显示的,标题则会高亮显示,如果内容是隐藏的,则会高亮显示新闻标题。