几种实现悬浮下拉菜单的方式

首先是HTML代码


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <link rel="stylesheet" type="text/css" href="index.css"/>
head>
<body>

<div id="nav" class="nav">
    <ul>
        <li><a href="#">网站首页a>li>
        <li><a href="#">课程大厅a>
            <ul>
                <li><a href="#">JavaScripta>li>
                <li><a href="#">jQuerya>li>
                <li><a href="#">Ajaxa>li>
            ul>
        li>
        <li><a href="#">学习中心a>
            <ul>
                <li><a href="#">视频学习a>li>
                <li><a href="#">案例学习a>li>
                <li><a href="#">交流平台a>li>
            ul>
        li>
        <li><a href="#">经典案例a>li>
        <li><a href="#">关于我们a>li>
    ul>
div>
body>
html>

第一种 HTML+CSS

div.nav {
    width:500px;

}

.nav ul {
    width:500px;
    overflow:hidden;
}

.nav ul li {
    width:100px;
    float:left;
    list-style:none;
}

.nav ul li ul {
    display:none;
}

a {
    color: #FFFFFF;
    display:inline-block;
    line-height:30px;
    height:30px;
    width:100px;
    background:red;
    text-decoration:none;
    text-align:center;
}



.nav ul li:hover ul {
    display:block;
    margin-left:0px;
    padding-left:0px;
}

.nav ul li:hover a{
    background-color:black;
}

.nav ul li:hover ul li {
    list-style:none;
    float:none;
    /*text-align:center;*/
}

.nav ul li:hover ul li a {
    color: #FFFFFF;
    display:inline-block;
    height:30px;
    width:100px;
    background:black;
    text-decoration:none;
    text-align:center;
}

.nav ul li:hover ul li:hover a {
    background-color:aqua;
}

基本就是通过伪类来做到

第二中方式 JS实现

window.onload = function(){
    var courseHall = document.getElementsByClassName("course-hall")[0];
    var learn = document.getElementsByClassName("learn")[0];

    console.log(courseHall);
    courseHall.addEventListener("mouseover",function(){
       var tar = this.getElementsByTagName("ul")[0]
        // console.log(tar);
        // console.log(event.target);
        tar.style.display = "block";
    },false);


    courseHall.addEventListener("mouseout",function(){
        var tar = this.getElementsByTagName("ul")[0]
        // console.log(tar);
        // console.log(event.target);
        tar.style.display = "none";
    },false);

    learn.addEventListener("mouseover",function(){
        var tar = this.getElementsByTagName("ul")[0]
        // console.log(tar);
        // console.log(event.target);
        tar.style.display = "block";
    },false);

    learn.addEventListener("mouseout",function(){
        var tar = this.getElementsByTagName("ul")[0]
        // console.log(tar);
        // console.log(event.target);
        tar.style.display = "none";
    },false);
}

也很简单,通过mouseout和mouseover来达到

你可能感兴趣的:(几种实现悬浮下拉菜单的方式)