(vue.js+css实现动态输出导航和下拉列表)
功能:
1.鼠标点击实现导航项选择,带有下拉列表的导航项无法直接通过鼠标点击选择,必须点击下拉选项
2.鼠标悬浮显示下拉列表
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- 导入vue.js -->
<script src="./js/vue.js"></script>
<!-- 导入样式 -->
<link rel="stylesheet" href="./css/head.css">
<!-- 没有用的element-ui -->
<!-- <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<script src="https://unpkg.com/element-ui/lib/index.js"></script> -->
</head>
<body>
<div class="head" id="head">
<span>
<img src="./images/search.ico"/>
<h1 class="title">页面标题
<span>测试</span>
</h1>
</span>
<span class="nav">
<ul >
<!-- 循环对象,输出导航项 -->
<li
v-for='(item,index) in navList'
:key='index'
>
<!-- 1.根据索引,给点击导航项改变样式
2. 给带下拉列表的导航项单独添加样式实现不允许点击 -->
<a
href="#"
:class= "{active: current === index, disable: item.flag}"
@click='change(index)'>
{{item.title}}
</a>
<!-- 根据flag判断是否存在下拉列表,存在则创建下拉列表 -->
<ul class="itemmenu" v-if='item.flag'>
<!-- 循环输出下拉列表项 -->
<li v-for='message in item.message ':key='message' @click='change(index)'><a href="#" >{{message}}</a></li>
</ul>
</li>
</ul>
</span>
</div>
<div class="main"></div>
<div class="foot"></div>
</body>
<script >
new Vue({
el: '#head',
data: {
navList:[
{
title:'首页',
flag: false,
message:[],
},
{
title:'产品',
flag: true,
message:
[
'我是选项1',
'我是选项11',
'我是选项111',
'我是选项1111',
]
},
{
title:'服务',
flag: true,
message:[
'我是选项11111',
'我是选项111111',
'我是选项1111111',
'我是选项11111111',
'我是选项111111111',
],
},
{
title:'动态',
flag: false,
message:[],
},
{
title:'关于',
flag: true,
message:[
'关于我们',
'加入我们'
],
}
],
current: 0
},
methods: {
change(index) {
this.current = index;
}
}
})
</script>
*{
margin: 0;
padding: 0;
}
/* 设置浏览器自带的滚动条不占宽高,页面长度够导航条出现就不用加*/
body::-webkit-scrollbar{
width:0;
}
.head {
background-color: rgb(13, 13, 241);
display: flex;
height: 60px;
line-height: 60px;
justify-content: space-between;
}
.head>span:first-child {
margin-left: 20px;
display: block;
min-width: 200px;
}
.head>span>h1 {
margin-left: 40px;
}
/* 图片使用绝对定位来实习居中 */
.head img {
position: absolute;
top: 14px;
border-radius: 50px;
}
.title {
color: rgb(96, 221, 221);
}
.title>span {
margin-left: 8px;
font-size: 16px;
}
/* 列表去除样式,使用flex布局实现同行显示 */
.nav>ul {
display: flex;
list-style: none;
}
.nav>ul>li {
margin-right: 10px;
}
.nav>ul>li:last-child {
margin-right: 100px;
}
.nav>ul>li>a{
color: white;
padding: 5px 10px;
}
.nav a{
text-decoration: none;
font-size: 18px;
}
.nav a:hover{
border-bottom: 2px solid rgb(176, 176, 241);
}
.itemmenu {
/* 隐藏下拉列表 */
display: none;
list-style: none;
position: absolute;
}
/* 实习鼠标悬浮导航出现下拉列表 */
.nav>ul>li:hover .itemmenu{
display: block;
background-color: rgb(165, 165, 245);
padding: 0 20px;
border-radius: 5px;
float: left;
}
/* 动态选择的导航样式 */
.active {
background-color: rgb(176, 176, 241);
border: 1px solid rgb(176, 176, 241);
border-radius: 2px;
}
/* 存在下拉列表选项的导航项不能直接点击选择 */
.disable {
pointer-events: none;
}