欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

js实现带简单弹性运动的导航条

程序员文章站 2022-05-25 19:04:33
...
晚上跟着视频敲了下 弹性菜单的代码,先记下来

效果如下:

js实现带简单弹性运动的导航条

代码如下:

<!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('.mark');
 var oBox = document.querySelectorAll('.box');
 var childUl = oMark.querySelector('ul');
 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 + 'px';
   childUl.style.left = -iTarget + 'px';
   iSpeed = 0;
  }else {
   oMark.style.left = oMark.offsetLeft + iSpeed +'px';
   childUl.style.left = -oMark.offsetLeft +'px';
  }
  },30);
 };
 };
</script>
</html>


更多js实现带简单弹性运动的导航条相关文章请关注PHP中文网!