首页 新闻 会员 周边 捐助

js模拟select, 如何阻止事件冒泡???

0
悬赏园豆:20 [已解决问题] 解决于 2013-06-20 16:04

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>select</title>
<style type="text/css">
*{margin:0;padding:0;}
body{font-size:12px;}
ul{list-style:none;}
.warp{width:400px; margin:100px auto;}
.selectbox{width:120px; height:25px; line-height:25px; cursor:pointer; border:1px solid #ddd; padding-left:10px; position:relative;}
#txt{display:block; width:120px;height:25px; line-height:25px;}
.select-list{ position:absolute; width:130px; left:-1px; border:1px solid #ddd; top:25px; display:none;}
.select-list li{padding:0 10px; height:30px; line-height:30px; cursor:pointer; overflow:hidden;}
.select-list li:hover{ background:#39F; color:#fff;}
</style>
<script type="text/javascript">
window.onload=function(){
    var oList = $('selectList');
    var oLi = oList.getElementsByTagName('li');
    var oTxt = $('txt');
    var oVal = $('val');
    
    oTxt.onclick=function(){
        if(oList.style.display=='block'){
            oList.style.display='none';
        }else{
            oList.style.display='block';
        }
        return false;    
    }
    for(var i=0;i<oLi.length;i++){
        oLi[i].onclick=function(){
            var str = this.innerHTML;
            oTxt.innerHTML = str;
            oVal.value = str;
            oList.style.display='none';
            return false;
        }
    }
    
    document.onclick=function(){
        //alert(0);
        oList.style.display='none';
    }
}
function $(id){
    return document.getElementById(id);
}
</script>
</head>

<body>
<div class="warp">
    <input type="hidden" value="" id="val"  />
    <div class="selectbox" id="selectBox">
        <span id="txt">请选择</span>
        <ul class="select-list" id="selectList">
            <li>读书</li>
            <li>电影</li>
            <li>音乐</li>
        </ul>
    </div>
</div>
</body>
</html>

 

 
当然感的主页 当然感 | 初学一级 | 园豆:43
提问于:2013-06-09 16:27
< >
分享
最佳答案
0

oTxt.onclick=function(evt){
        if(oList.style.display=='block'){
            oList.style.display='none';
        }else{
            oList.style.display='block';
        }
        if (evt) {
            evt.stopPropagation();
        } else {
             window.event.cancelBubble = true;
        }
}

把这一段改一下 。

收获园豆:20
木头小木头 | 菜鸟二级 |园豆:284 | 2013-06-09 23:40
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册