Use Javascrip to write the selelct drop-down menu effect
Not much to say, first on the renderings:
html code:
<p>2.模拟selelct下拉菜单</p>
<div class="twobox">
<div id="twoboxsamll">
请选择游戏名称
<input type="text" id="wenben" onclick="dInput()">
<input type="button" value="搜索">
</div>
<ul id="oul">
<li>共和国之辉</li>
<li>侠盗猎车</li>
<li>英雄联盟</li>
<li>QQ飞车</li>
<li>QQ炫舞</li>
</ul>
</div>
CSS code:
.twobox{
width: 100%;
height: 500px;
background-color: grey;
margin: 0 auto;
}
#twoboxsamll{
width: 350px;
height:25px;
margin: 0px auto;
}
#wenben{
border-radius: 15px;`在这里插入代码片`
outline: none;
}
#oul{
border: 1px solid white;
width: 170px;
list-style: none;
position: relative;
background: burlywood;
left: 615px;
display: none;
}
#oul li{
border-bottom: 1px dashed white;
cursor: pointer;
}
Javascript code:
let oul = document.getElementById("oul");
let wenben = document.getElementById("wenben");
let oli = document.getElementById("oul").children;
function dInput(evt){
let e = evt || event; //为了让多数浏览器都兼容,所以用事件的兼容写法
oul.style.display = "block";
e.stopPropagation?e.stopPropagation():e.cancelBubble=true; //阻止事件冒泡
}
for(let j=0;j<oli.length;j++){ //循环每个Li,
oli[j].onclick = function(evt){ //点击哪个Li让哪个Li做相应的操作
let e = evt || event; //为了让多数浏览器都兼容,所以用事件的兼容写法
wenben.value=this.innerHTML;//把点击的Li的内容传给文本框
oul.style.display = "none"; //点击选择之后将ul隐藏
}
}
document.onclick = function(evt){ //点击界面的任何一个地方让ul隐藏
let e = evt || event;
oul.style.display = "none";
}
This involves an event bubbling: For details, please see: Event bubbling and preventing event bubbling