老师哪里可以改进下
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> * { margin: 0; padding: 0; } a { text-decoration: none; } .head { width: 1100px; height: 80px; margin: 0 auto; overflow: hidden; clear: both; } h1 { float: left; line-height: 80px; } .header-nav { float: right; width: 360px; height: 32px; position: relative; top: 50%; margin-top: -15px; } .header-nav .nav-list { float: left; width: 290px; height: 30px; } .header-nav .nav-list li { float: left; list-style: none; margin-right: 25px; line-height: 30px; height: 30px; width: 32px; } .header-nav .carousel { position: absolute; height: 3px; width: 32px; background-color: red; bottom: 0px; left: 0px; display: none; transition: left .3s ease 0s; } .header-nav .nav-list li a { color: black; display: block; height: 32px; } .header-nav .nav-list li a.current { color: red; } .header-nav .buy-button { float: left; width: 70px; background-color: black; color: white; border-radius: 4px; border: none; line-height: 30px; } </style> </head> <body> <section class="head"> <h1>慕课手机</h1> <nav class="header-nav"> <ul class="nav-list" id="nav-list"> <li><a href="javaScript:;" data-t="front">首页</a></li> <li><a href="javaScript:;" data-t="show">外观</a></li> <li><a href="javaScript:;" data-t="config">配置</a></li> <li><a href="javaScript:;" data-t="model">型号</a></li> <li><a href="javaScript:;" data-t="illus">说明</a></li> </ul> <div class="carousel" id="carousel"></div> <button class="buy-button">立即购买</button> </nav> </section> <script> var navList = document.getElementById('nav-list'); var navlis = navList.getElementsByTagName('a'); var carousel =document.getElementById('carousel'); navList.onmouseover = function (e) { if (e.target.tagName.toLowerCase() == 'a') { //先进行排他操作 for (var i = 0; i < navlis.length; i++) { navlis[i].className = ''; } e.target.className = 'current'; //获取触碰到的data-t值 var idx = e.target.getAttribute('data-t'); //定义left移动距离 var left; switch (idx) { case 'front': left = 0; break; case 'show': left = 57; break; case 'config': left = 114; break; case 'model': left = 171; break; case 'illus': left = 228; break; default: carousel.style.display = 'none'; } carousel.style.left = left + 'px'; carousel.style.display = 'block'; } } navList.onmouseleave =function(){ for (var i = 0; i < navlis.length; i++) { navlis[i].className = ''; } carousel.style.display = 'none'; } </script> </body> </html> 问题描述:我的data-t属性和class=“current”写在a标签里面,因为我发现写在li标签里的话,移动到a标签上的时候效果不显示,e.target.tagName也只获取到a标签,可以把data-t和current类写在li标签里面吗?怎么操作呢
10
收起
正在回答
1回答
同学你好,解答如下:
1、代码可以优化:
(1)默认第一个导航‘首页’是激活状态,可以给a添加上current类
(2)用switch有些复杂,可以用data-index设置值为数字,然后与57相乘进行left值设置
2、e.target获取的是当前移入的元素,所以是a元素。如果想设置在li上,可以用e.target.parentNode,找到父节点。参考(在第一步的基础上修改的):
css修改
js修改:
自己再测试下,祝学习愉快!
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星