自己写的jQuery实现下拉列表,有事件冒泡,带有比较详细的注释

来源:互联网 发布:淘宝店铺装修在哪里 编辑:程序博客网 时间:2024/06/07 06:08
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="js/jquery-1.7.1.js"></script>




<title></title>
<script type="text/javascript" >
$(document).ready(function(){
var _id="p1";
$("#_select").click(function(event){
if($("#_option").css("display")=="none")//这对if else 点击复选框,判断下拉表是否出现,如果已经出现,则隐藏,如果没有出现则显示
$("#_option").slideDown('fast');
else
$("#_option").slideUp('fast');
$(document).one("click",function(){  //给DOM元素绑定一个click事件,当页面有点击行为发生时候,就会冒泡,执行这个函数,也就是鼠标在复选框其他的位置点击,下拉表会消失。
$("#_option").hide();
});
event.stopPropagation();//因为复选框DOM元素也属于整个的document,所以当点击的时候,防止事件冒泡触发上面的Documentde click事件

});


$("#_option p").mouseover(function(){
$(this).css("background-color","#ccc");
})
$("#_option p").mouseleave(function(){
if($(this).attr("id")==_id)
   $(this).css("background-color","#ccc");
    else
    $(this).css("background-color","#ffffff");
})


$("#_option p").click(function(){

_id=$(this).attr("id");
$("#_option p").each(function(){
if($(this).attr("id")==_id) //标记,对下拉表中选定的元素进行背景强调
$(this).css("background-color","#ccc");
else 
$(this).css("background-color","#ffffff");
$("#_option").css("display","none");
})
var txt=$(this).text();
$("#_select").html(txt);

})
$("#_option").click(function(event){  //避免点击触发Document的click事件

event.stopPropagation();
}); 
})


</script>
<style type="text/css">
#_select{
box-sizing:border-box;
border:1px solid #666;
width:150px;
height:30px;
    margin:0;
padding:0;
padding-top:5px;
background:url(img/1.png) no-repeat;
background-position:-90px -5px;
}
#_option {
border:1px solid #666;
width:150px;
height:100px;
margin:0;
padding:0;
display:none;
}
#_option p {
    line-height:20px;
margin:0;
padding:0;
}
</style>
</head>
<body>
<br><br>点击下面按钮查看预览效果:
<div id="_select">请选择</div>
<div id="_option">
<p id="p1">1</p>
<p id="p2">2</p>
<p id="p3">3</p>
<p id="p4">4</p>
</div>
</body>
</html>
0 0