search
HomeWeb Front-endHTML Tutorial用css+js实现自动伸缩导航栏_html/css_WEB-ITnose

作者的话

偶然一个机会,在网上看到一篇ted公开课【让我们教孩子编程吧】里面有一个实例,说是一个小男孩制作了一个大鱼吃小鱼的游戏,他想为这个游戏做一个计分板(吃一条鱼加一分),便他在网上求教,后来被网站创作者发现后,告诉了他答案:变量。通过这个学到的知识点【变量】也许小男孩永远不会忘记。

从中可以看出,通过需求学习编程往往比为了学编程而学习编程要记得更劳并且更有价值。这也对我之后的学习以及写作产生的改变。

PS:以下代码每次只写出有更改的地方,无更改的地方不再赘述。每一部分的格式都是:效果图——思路——代码的顺序书写,目的是希望初学者可以根据效果图,辅以思路试着自己写出代码,最后再与作者的代码作比较,希望能通过这个方法明白,实现效果的方式是多种多样的,不要只局限在作者的思路中,当然最重要的是能锻炼自己编写代码的能力。

任务概述

需要达到的效果

task goal_1

task goal_2

  1. 默认首页选中样式;
  2. 设置鼠标滑过效果:颜色变化(#f60),宽度变化,字体变化。

所涉及知识点

  1. 布局:float;
  2. css:元素状态切换(display),盒模型(margin,padding),圆角边框(border-radius),可见宽(offsetWidth);3.JavaScript:匿名类,for循环,通过标签获得元素(getElementsByTagName), 方法自动间隔运行(setInterval/clearInterval)。

基本架构

这是一个没有任何css修饰的html代码

3

无序列表:

  • ,是与导航栏语义比较贴切的标签,然后将标签放到
  • 内部即可实现导航栏html部分。
    <ul class="nav" >        <li><a href="#">首    页</a></li>        <li><a href="#">新闻快讯</a></li>        <li><a href="#">产品展示</a></li>        <li><a href="#">售后服务</a></li>        <li><a href="#">联系我们</a></li>    </ul>

    这是导航栏默认样式,我们通过css进行初步修改

    样式修改

    取消默认样式

    4

    把浏览器默认的盒模型值,列表样式以及链接样式的默认样式取消,并且把字体颜色改成黑色。

        *{margin: 0;padding: 0;          font-size: 14px;}    li{list-style: none;}    a{text-decoration: none;           color: #000;}

    设置骨架

    5

    1. 通过将设置成块状标签,即可达到给设置宽高的目的;
    2. 通过float:left使导航栏从纵向排列变成横向排列;
    3. 通过将line-height属性设置的跟height一样,实现导航栏文字垂直居中;
    4. 通过text-aligin将导航栏文本水平居中。
    li{list-style: none;float:left;}li a{display:block;width: 100px;     height: 30px;line-height: 30px;     text-aligin:center;    }

    颜色以及细节修改

    6

    1. 设置导航栏默认颜色,并且通过margin属性是导航标签产生间隔。
    2. 将导航栏四个角通过border-radius设置成圆角。
    3. 通过给属性设置class=on,以及伪类选择器a:hover将【首页】和【鼠标滑过】的样式颜色设置为#f60,字体颜色设置为白色。
    li a{display:block;width: 100px;      height: 30px;line-height: 30px;      background-color: #efefef;      margin-left:1px;}.on,.nav li a:hover{    background-color: #f60;     color: #fff;}

    设置导航栏的“脚”

    7

    1.通过border-bottom属性制作导航栏的“脚”;

    1. 要知道我们已经将
    2. 设置成了float,因此它已经脱离了文本档,那么其父元素的默认height值也就为0,需要自己设定;3.通过margin,padding属性移动导航栏主体部分。
    ul{height:50px;    border-bottom:5px solid #f60;    padding-left:20px;}li{margin-top:20px;}

    鼠标划过改变行高

    8

    1. 通过hover设置鼠标划过后的行高2.此时会发现导航栏向下移动了,通过将margin设置为负值,向上移动。
    .on,.nav li a:hover{   height: 40px;   line-height: 40px;   margin-top: -10px;}

    以上是css部分,下面讲JavaScript。

    鼠标划过自动伸缩

    分为两部分来写:自动伸和自动缩

    鼠标划过自动伸

    9

    效果:鼠标划过导航栏自动延伸。

    1. 首先要获得标签元素,可以通过getElementsByTag;
    2. 要给每一个标签设置,可以通过for循环遍历;
    3. 鼠标划过事件通过 onmouseover设置;
    4. 在方法里通过var变量获得当前标签元素。
    5. 设置自动延伸,可以通过setInterval方法,让方法以固定的时间为间隔,反复执行;
    6. 此时导航栏会无限延伸,通过if设置条件,设置导航栏延伸停止时机。
    window.onload=function(){    var aA=document.getElementsByTagName("a");    for(var i=0;i<aA.length;i++){        aA[i].onmouseover=function(){            var This=this;            clearInterval(This.time);//初始化            This.time=setInterval(function(){                This.style.width=This.offsetWidth+8+"px";                    if(This.offsetWidth>=150){                    clearInterval(This.time)                    }                },30);            }        }    }

    鼠标离开自动缩

    最终图片,与文章开头图片相同效果:鼠标离开导航栏自动缩到原始状态。

    1. 思路同上,只是数值相反。
    aA[i].onmouseout=function(){    var This = this;    clearInterval(This.time);//初始化        This.time=setInterval(function(){        This.style.width=This.offsetWidth-8+"px";            if(This.offsetWidth<=100){                clearInterval(This.time);            }        },30);    }}

    最终代码

    <!DOCTYPE html><html><head>    <meta http-equiv="Content-Type" content="text/html" charset="UTF-8">    <title>导航栏v1.0</title>    <style type="text/css">        /*@group general style*/        *{margin: 0;padding: 0;font-size: 14px;}        a{color: #333;text-decoration: none;}        ul{            list-style: none;border-bottom: 5px solid #f60;height: 50px;            padding-left: 30px;        }        li{            margin-top:20px;            float: left;}        /*@group overrides*/        .nav li a{            display: block;            text-align: center;            height: 30px;            line-height:30px;            width: 120px;            background-color: #efefef;                        border-radius: 5px;        }        .nav .on,.nav li a:hover{            color: #fff;            background-color: #f60;            height: 40px;            line-height: 40px;            margin-top: -10px;        }    </style></head><body>    <ul class="nav" >        <li><a class="on" href="#">首    页</a></li>        <li><a href="#">新闻快讯</a></li>        <li><a href="#">产品展示</a></li>        <li><a href="#">售后服务</a></li>        <li><a href="#">联系我们</a></li>    </ul>    <script type="text/javascript">    window.onload=function(){        var aA=document.getElementsByTagName("a");        for(var i=0;i<aA.length;i++){            aA[i].onmouseover=function(){                // 设置方法停止的时机                clearInterval(this.time);                // 此处this为当前a标签                var This=this;                // 设置方法每30毫秒运行一次                // 其中offsetWidth:对象的可见宽度,包括本身width+padding-border                // 当offsetWidth>=120时,程序停止。                This.time=setInterval(function(){                    This.style.width=This.offsetWidth+8+"px";                    if(This.offsetWidth>=160){                    clearInterval(This.time);                }                },30);            }            aA[i].onmouseout=function(){                clearInterval(this.time);//初始清理                var This=this;                This.time=setInterval(function(){                    This.style.width=This.offsetWidth-8+"px";                    if(This.offsetWidth<=120){                        clearInterval(This.time);                    }                },30);            }            }    }    </script></body></html>

    注:此项目灵感来自慕课网

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
HTML: The Structure, CSS: The Style, JavaScript: The BehaviorHTML: The Structure, CSS: The Style, JavaScript: The BehaviorApr 18, 2025 am 12:09 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

The Future of HTML: Evolution and Trends in Web DesignThe Future of HTML: Evolution and Trends in Web DesignApr 17, 2025 am 12:12 AM

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

HTML vs. CSS vs. JavaScript: A Comparative OverviewHTML vs. CSS vs. JavaScript: A Comparative OverviewApr 16, 2025 am 12:04 AM

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

HTML: Is It a Programming Language or Something Else?HTML: Is It a Programming Language or Something Else?Apr 15, 2025 am 12:13 AM

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML: Building the Structure of Web PagesHTML: Building the Structure of Web PagesApr 14, 2025 am 12:14 AM

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

From Text to Websites: The Power of HTMLFrom Text to Websites: The Power of HTMLApr 13, 2025 am 12:07 AM

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

Understanding HTML, CSS, and JavaScript: A Beginner's GuideUnderstanding HTML, CSS, and JavaScript: A Beginner's GuideApr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

The Role of HTML: Structuring Web ContentThe Role of HTML: Structuring Web ContentApr 11, 2025 am 12:12 AM

The role of HTML is to define the structure and content of a web page through tags and attributes. 1. HTML organizes content through tags such as , making it easy to read and understand. 2. Use semantic tags such as, etc. to enhance accessibility and SEO. 3. Optimizing HTML code can improve web page loading speed and user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor