02-原生js筋斗云案例

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

<style>
* {
  margin: 0;
  padding: 0
}
ul {
  list-style: none
}
body {
  background-color: #333;
}
.nav {
  width: 800px;
  height: 42px;
  margin: 100px auto;
  background: url(images/rss.png) right center no-repeat;
  background-color: #fff;
  border-radius: 10px;
  position: relative;
}
.nav li {
  width: 83px;
  height: 42px;
  text-align: center;
  line-height: 42px;
  float: left;
  cursor: pointer;
}
.nav span {
  position: absolute;
  top: 0;
  left: 0;
  width: 83px;
  height: 42px;
  background: url(images/cloud.gif) no-repeat;
}
ul {
  position: relative;
}

</style>

</head>
<body>

<!--html代码-->
<div class="nav">
  <span id="cloud"></span>
  <ul id="navBar">
    <li>北京校区</li>
    <li>上海校区</li>
    <li>广州校区</li>
    <li>深圳校区</li>
    <li>武汉校区</li>
    <li>关于我们</li>
    <li>联系我们</li>
    <li>招贤纳士</li>
  </ul>
</div>
<!--js代码-->
<script>
//根据id获取对应的元素
  function my$(id) {
    return document.getElementById(id);
  }
// 获取云彩
var cloud = my$("cloud"); 
// 获取所有的li标签
var list = my$("navBar").children;  
// 循环遍历分别注册  鼠标进入  鼠标离开  ,点击事件
for (let i = 0; i < list.length; i++) { 
  list[i].onmouseover = mouseoverHandle;  // 鼠标进入事件
  list[i].onclick = clickHandle;  // 点击事件
  list[i].onmouseout = mouseoutHandle;  // 鼠标离开事件
}
// 鼠标进入
function mouseoverHandle() {  
  animate(cloud,this.offsetLeft);
}
// 点击的时候,记录上次的位置
var lastPosition = 0; 
// 点击事件
function clickHandle() {  
  lastPosition = this.offsetLeft;
}
// 鼠标离开
function mouseoutHandle() { 
  animate(cloud, lastPosition  );
}
// 变速动画
// 获取元素的当前位置,移动,每次移动多少像素
function animate(element, target) {
  //每次调用这个函数的时候先清理之前的计时器
  clearInterval(element.timeId);
  // 定时器
  element.timeId = setInterval(() => {
    //获取元素当前的位置
    var current = element.offsetLeft;
    //每次移动的像素 = 目标位置 - 元素当前位置  / 10
    var step = (target - current) / 10;
    //判断移动的步数 是向下取整还是向上取整
    step = step > 0 ? Math.ceil(step) : Math.floor(step);
    // 当前位置 += 每次移动的步数
    current += step;
    // 元素据左边距离 = 当前位置 + px
    element.style.left = current + "px";
    // 如果当前位置等于目标位置
    if (current == target) {
      // 清理定时器
      clearInterval(element.timeId)
    }
  }, 20);
}
</script>

</body>
</html>

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容