Home  >  Article  >  Web Front-end  >  js implements navigation bar with simple elastic movement

js implements navigation bar with simple elastic movement

高洛峰
高洛峰Original
2017-02-23 17:27:081342browse

At night, I typed the code for the flexible menu following the video, and wrote it down first

The effect is as follows:

js implements navigation bar with simple elastic movement

The code is as follows:

<!doctype html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Document</title>
 <style>
 *{
  margin:0;
  padding:0;
 }
 .ul1{
  width:450px;
  height:30px;
  margin:20px auto;
  position:relative;
 }
 li{
  list-style:none;
  line-height:30px;
  height:30px;
  width:100px;
  color:orange;
  text-align:center;
  float:left;
  margin-right:5px;
  border:1px soli #000;
  background-color:red;
 }
 .mark{
  position:absolute;
  left:0;
  top:0;
  overflow:hidden;
 }
 .mark ul{
  width:450px;
  position:absolute;
  left:0;
  top:0;
 }
 .mark ul li{
  color:#fff;
  background-color:deepskyblue;
 }
 </style>
</head>
<body>
<ul class="ul1">
 <li class="mark">
 <ul>
  <li>首页</li>
  <li>论坛</li>
  <li>视频</li>
  <li>课程</li>
 </ul>
 </li>
 <li class="box">首页</li>
 <li class="box">论坛</li>
 <li class="box">视频</li>
 <li class="box">课程</li>
</ul>
</body>
<script>
 window.onload = function(){
 var oMark = document.querySelector(&#39;.mark&#39;);
 var oBox = document.querySelectorAll(&#39;.box&#39;);
 var childUl = oMark.querySelector(&#39;ul&#39;);
 var timer = null;
 var timer2 = null;//延迟定时器,100毫秒人的眼睛是察觉不出来的
 var iSpeed = 0;
 for (var i=0;i<oBox.length;i++){
  oBox[i].onmouseover = function(){
  clearTimeout(timer2);
  startMove(this.offsetLeft);
  };
  oBox[i].onmouseout = function(){
  timer2 = setTimeout(function(){
   startMove(0);
  },100);

  };
 }
 oMark.onmouseover = function(){
  clearTimeout(timer2);
 };
 oMark.onmouseout= function(){
  timer2 = setTimeout(function(){
  startMove(0);
  },100);
 };
 function startMove(iTarget){
  clearInterval(timer);
  timer = setInterval(function(){
  iSpeed += (iTarget -oMark.offsetLeft)/5;
  iSpeed *= 0.75;
  if(Math.abs(iSpeed)<=1 && Math.abs(iTarget -oMark.offsetLeft)<=1){
   clearInterval(timer);
   oMark.style.left = iTarget + &#39;px&#39;;
   childUl.style.left = -iTarget + &#39;px&#39;;
   iSpeed = 0;
  }else {
   oMark.style.left = oMark.offsetLeft + iSpeed +&#39;px&#39;;
   childUl.style.left = -oMark.offsetLeft +&#39;px&#39;;
  }
  },30);
 };
 };
</script>
</html>


For more js-related articles about implementing a navigation bar with simple elastic movement, please pay attention to the PHP Chinese website!

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