js练习 DIV做下拉列表

<html>
<head>
<meta charset="utf-8">
<title>下拉列表</title>
<style type="text/css">
  *{margin:0px auto; padding:0;}
  #wai{width:300px; height:300px;}
  #txt{width:190px; height:30px; margin-top:20px; padding-left:5px; padding-right:5px; border:1px solid red; line-height:30px;}
  #xl{width:202px; height:150px; display:none;}
  .list{width:190px; height:30px;padding-left:5px; padding-right:5px; border:1px solid red; line-height:30px; border-top:none;}
</style>
</head>

<body>
    <div id="wai">
        <div id="txt">中国</div>
        <div id="xl">
            <div class="list">北京</div>
            <div class="list">上海</div>
            <div class="list">广州</div>
            <div class="list">浙江</div>
            <div class="list">山东</div>
        </div>
    </div>

</body>
</html>
<script type="text/javascript">
    var txt = document.getElementById("txt");
    var xl = document.getElementById("xl");
    /*
        点文本框击显示下拉列表
    */
    txt.onclick = function()
    {
        xl.style.display = "block";
    }
    
    var list = document.getElementsByClassName("list")
    /*
        点击下拉列表选项,隐藏下拉列表并且点击的选项的文字显示在文本框内
    */
    for(var i=0;i<list.length;i++)
    {
        list[i].onclick = function()
        {
            xl.style.display = "none";
            txt.innerText = this.innerText;
        }
    }

</script>

  

 

posted @ 2017-12-07 16:12  黑山大胖子  阅读(745)  评论(0编辑  收藏  举报