开发者社区 问答 正文

一个简单的js动效?

screenshot
如图,想实现一个很简单的效果,鼠标点击某一块的时候,左边的黄线就会移动到该块的左边。黄线是绝对定位的块,通过修改top的值进行移动,本人技术菜,能想到最简洁的代码就是这么写了,而且这种写法估计也就只能用在静态页面,我想知道更简洁更具有扩展性的代码应该怎么写?获取鼠标位置之类的……
谢谢~~

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <section>
    <div id="id1">1</div>
    <div id="id2">2</div>
    <div id="id3">3</div>
    <div id="id4">4</div>
    <div id="id5">5</div>
    <i id="line" style="top: 90px;"></i>
  </section>
</body>
</html>

//js
function avtiveLineTop(n) {
  document.getElementById('line').style.top = n + 'px';
};

document.getElementById('id1').onclick = function() {
  avtiveLineTop(0);
};
document.getElementById('id2').onclick = function() {
  avtiveLineTop(51);
};
document.getElementById('id3').onclick = function() {
  avtiveLineTop(102);
};
document.getElementById('id4').onclick = function() {
  avtiveLineTop(153);
};
document.getElementById('id5').onclick = function() {
  avtiveLineTop(204);
};

展开
收起
a123456678 2016-03-11 17:40:24 2580 分享 版权
1 条回答
写回答
取消 提交回答
  • 这个可以使用到事件代理,我是这样实现的,希望对你有你帮助

     <section>
       <div id="item1">
        <div id="id1" class="item">1</div>
        <div id="id2"class="item">2</div>
        <div id="id3"class="item">3</div>
        <div id="id4"class="item">4</div>
        <div id="id5"class="item">5</div>
        </div>
        <div id="line" ></div>
      </section>
    
    
    <script>
        function avtiveLineTop(n) {
      document.getElementById('line').style.top = n + 'px';
    };
          var item1=document.getElementById("item1");
              item1.addEventListener("click",handle,false);
             function handle(event){
                  var event=event||window.event;
                    var target=event.target||event.srcElement;;
                    switch(target.id){
                        case "id1":
                           avtiveLineTop(0);   
                       break;
                       case "id2":
                            avtiveLineTop(51);
                       break;
                        case "id3":
                           avtiveLineTop(102);
                       break;
                         case "id4":
                         avtiveLineTop(153);
                       break;
                       case "id5":
                           avtiveLineTop(204);
                       break;
    
    
                           
                    }
                       }
        
          </script>
    2019-07-17 18:59:45
    赞同 展开评论
问答分类:
问答标签:
问答地址: