阅读(726)
赞(16)
js下拉菜单制作
2016-08-10 16:36:04 更新
一、用js通过下拉菜单来实现div的隐藏和显示
思路:利用value属性获取下拉菜单的选项→根据选项决定div的状态→利用style.display样式隐藏或显示div。实例演示如下:
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>W3Cschool(zijiebao.com)</title>
</head>
<body>
<select id="test_select">
<option value="1">显示</option>
<option value="2">隐藏</option>
</select>
<div id="test">我是一个div么呀我是一个div</div>
<script>
window.onload = function () {
var obj_select = document.getElementById("test_select");
var obj_div = document.getElementById("test");
obj_select.onchange = function () {
obj_div.style.display = this.value == 1 ? "block" : "none";
}
}
</script>
</body>
</html>
效果演示
二、鼠标滑过出现下拉菜单的js做法
大致思路如下:先给菜单box定好宽高加上position:relative;再给里面的内容定上与之相同的宽高;然后给里面的下拉 二级菜单加上宽度绝对定位。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>W3Cschool(zijiebao.com)</title>
<style>
* {
margin: 0;
padding: 0;
}
li {
list-style-type: none;
}
a {
text-decoration: none;
font-size: 14px;
}
.nav {
margin: 100px;
}
.nav>li {
position: relative;
float: left;
width: 80px;
height: 41px;
text-align: center;
}
.nav li a {
display: block;
width: 100%;
height: 100%;
line-height: 41px;
color: #333;
}
.nav>li>a:hover {
background-color: #eee;
}
.nav ul {
display: none;
position: absolute;
top: 41px;
left: 0;
width: 100%;
border-left: 1px solid #FECC5B;
border-right: 1px solid #FECC5B;
}
.nav ul li {
border-bottom: 1px solid #FECC5B;
}
.nav ul li a:hover {
background-color: #FFF5DA;
}
</style>
</head>
<body>
<ul class="nav">
<li>
<a href="javascript:;">下拉</a>
<ul>
<li><a href="javascript:;">下拉1</a></li>
<li><a href="javascript:;">下拉2</a></li>
<li><a href="javascript:;">下拉3</a></li>
<li><a href="javascript:;">下拉4</a></li>
</ul>
</li>
</ul>
<script>
var lis = document.querySelector('.nav').children;
for (var i = 0; i < lis.length; i++) {
lis[i].onmouseover = function () {
this.children[i].style.display = 'block';
}
lis[i].onmouseout = function () {
this.children[i].style.display = 'none';
}
}
</script>
</body>
</html>
← js幻灯片