js阻止事件冒泡實現遊戲選擇

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}

#d1 {
width: 500px;
height: 300px;
background: blue;
margin: auto;
margin-top: 50px;
border: 1px solid #cccccc;
position: relative;
}

#d2 {
width: 480px;
margin-left: 10px;
margin-top: 10px;
height: 50px;
background: #b0b0b0;
border: 1px solid #cccccc;
position: relative;
}

#d2 img {
margin-top: 13px;
margin-left: 10px;
float: left;

}

#inp {
margin-top: 8px;
margin-left: 5px;
width: 333px;
background: #767676;
height: 30px;
float: left;
color: #fff;

}

p {
/* width: 10px;
height: 10px; */
width: 1px;
height: 1px;
/* background: orange; */
border: 10px solid;
border-color: #bebebe transparent transparent transparent;
position: absolute;
top: 21px;
right: 108px;
cursor: pointer;
}

#inp2 {
width: 88px;
height: 34px;
float: left;
margin-top: 8px;
margin-left: 5px;
}

ul,
li {
list-style: none;
}

#u1 {
width: 334px;
height: 200px;
/* background: yellow; */
position: absolute;
left: 51px;
top: 51px;
display: none;
cursor: pointer;
overflow: auto;
}

#u1 li {
width: 100%;
height: 31px;
background: #58bc58;
border: 1px solid #cccccc;

}

.cl {
background: lightcoral;
}
</style>
<script>
window.onload = function () {
var inp = document.getElementById("inp");//獲取節點
var p1 = document.getElementById("p1");
var u1 = document.getElementById("u1");
var lis = u1.getElementsByTagName("li");
// console.log(u1, lis);
// console.log(inp, p1);
var isok = true;//設置開關
p1.onclick = function (ev) {//按鈕點擊事件,記得傳參否則 阻止冒泡用不了
if (isok) {//開關的狀態爲ture
u1.style.display = "block";//顯示u1
} else {//不然
u1.style.display = "none";//隱藏u1
}
isok = !isok;//開關取反;
ev.stopPropagation();//阻止冒泡 防止其餘的點擊事件形成的影響
}
document.onclick = function (ev) {//點擊不在做用範圍的時候隱藏
u1.style.display = "none";
isok = !isok;//開關取反

}

for (var i = 0; i < lis.length; i++) {//循環綁定事件
//lis[i].index = i;//綁定索引
lis[i].onclick = function (ev) {
inp.value = this.innerHTML;//把li的值寫進INOUT
// ev.stopPropagation();

}
}




}
</script>
</head>

<body>
<div id="d1">
<div id="d2">
<img src="images/01_03.png" alt="">
<input type="text" id="inp" placeholder="請選擇遊戲名稱">
<input type="button" value="搜索" id="inp2">
<p id="p1"></p>
</div>
<ul id="u1">
<li>狡詐惡徒</li>
<li>均衡只是一個謊話</li>
<li>陷陣之志,有死無生</li>
<li>精準與否就是手術和屠宰的區別</li>
<li>我用雙手成就你的夢想</li>
<li>死亡如風,常伴吾身</li>
<li>恕瑞瑪你的皇帝回來了</li>
<li>斷劍重鑄之日,騎士歸來之時</li>
<li>我渴望有價值的對手</li>

</ul>
</div>
</body>

</html>
相關文章
相關標籤/搜索