JavaScript原生程式碼實現導航欄小效果
阿新 • • 發佈:2019-01-03
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> *{ padding: 0; margin: 0; } body{ background-color: rgba(0,0,0,0.7); } ul{ position: relative; } li{ list-style: none; float: left; width: 83px; height: 42px; text-align: center; cursor: pointer; font: 400 16px/42px microsoft yahei; } .box{ width: 664px; height: 42px; margin: 200px auto; background: #fff ; position: relative; border-radius: 7px; } span{ position: absolute; width: 83px; height: 42px; left: 0; top: 0; border-radius: 7px; background-color:pink; } </style> <script> window.onload = function () { // 獲取相關元素 var btn = document.getElementsByTagName("span")[0]; var ul = document.getElementsByTagName("ul")[0]; var liarr = ul.children; var liwidth = liarr[0].offsetWidth; //獲取相關元素,繫結事件,書寫事件驅動程式 var raw = 0; for (var i = 0; i<liarr.length ;i++){ // 給元素繫結index屬性; liarr[i].index = i; liarr[i].onmouseover = function () { animate(btn,this.index*liwidth); } liarr[i].onmouseout = function () { animate(btn,raw*liwidth); } liarr[i].onclick = function () { raw = this.index; } } //緩動動畫封裝 function animate(ele,target) { clearInterval(ele.timer); ele.timer = setInterval(function () { var step = (target-ele.offsetLeft)/10; step = step>0?Math.ceil(step):Math.floor(step); ele.style.left = ele.offsetLeft + step + "px"; console.log(1); if(Math.abs(target-ele.offsetLeft)<Math.abs(step)){ ele.style.left = target + "px"; clearInterval(ele.timer); } },18); } } </script> </head> <body> <div class="box"> <span></span> <ul> <li>首頁新聞</li> <li>首頁新聞</li> <li>首頁新聞</li> <li>首頁新聞</li> <li>首頁新聞</li> <li>首頁新聞</li> <li>首頁新聞</li> <li>首頁新聞</li> </ul> </div> </body> </html>