亲宝软件园·资讯

展开

js实现缓动动画

小小小菜鸡zzzz 人气:0

利用定时器来控制元素的offsetLeft的值,offsetLeft = 开始位置 + (最终位置 - 开始位置)* 缓动系数

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>

 <style>
 * {
  margin: 0;
  padding: 0;
  border: none;
  list-style: none;
 }

 body {
  background-color: pink;
 }

 #nav {
  width: 900px;
  height: 63px;
  background: url("images/doubleOne.png") no-repeat right center #fff;
  margin: 0 auto;
  margin-top: 50px;
  border-radius: 5px;
  position: relative;
 }

 #nav ul {
  line-height: 70px;
 }

 #nav ul li {
  float: left;
  height: 63px;
  width: 88px;
  text-align: center;
  cursor: pointer;
  position: relative;
 }

 #t_mail {
  width: 88px;
  height: 63px;
  background: url("images/tMall.png") no-repeat;
  position: absolute;
 }
 </style>
</head>
<body>
 <nav id="nav">
 <span id="t_mail"></span>
  <ul>
  <li>双11狂欢</li>
  <li>服装会场</li>
  <li>数码家电</li>
  <li>母婴童装</li>
  <li>手机会场</li>
  <li>美妆会场</li>
  <li>家居建材</li>
  <li>进口会场</li>
  <li>飞猪旅行</li>
  </ul>
 </nav>

 <script>
 window.onload = function () {
  var nav = $('nav');
  var t_mall = nav.children[0];
  var ul = nav.children[1];
  var allLis = ul.children;
  var beginX = 0;

  for (var i = 0; i < allLis.length; i++) {
  var li = allLis[i];
  li.onmouseover = function () {
   end = this.offsetLeft;
  }

  li.onmousedown = function () {
   beginX = this.offsetLeft;
  }

  li.onmouseout = function () {
   end = beginX;
  }
  }

  var begin = 0, end = 0;
  setInterval(function () {
  begin = begin + (end - begin) / 10;
  t_mall.style.left = begin + 'px';
  }, 10)

  function $(id) {
  return typeof id ? document.getElementById(id) : null;
  }
 }
 </script>
</body>
</html>

加载全部内容

相关教程
猜你喜欢
用户评论