JS---案例:点击按钮摇起来

案例:点击按钮摇起来

思路:

1. 2张图片,放进div里面,摇起来的本质是,此div按上下左右的位置和在一定的时间内发生移动

2. 所以用随机数的概念来实现位置的移动,用setInterval来实现一定的时间区间,前者封装在后者的处理 函数里面。最后全部作为点击按钮的点击事件的处理函数

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>title</title>
  <style>
    img {
      width: 200px;
      height: 200px;
    }

    div {
      position: absolute;
    }
  </style>
</head>

<body>
  <input type="button" value="点击摇起来" id="btn1" />
  <input type="button" value="停止" id="btn2" />
  <div id="dv">
    <img src="images/tianshi.gif" alt="" />
    <img src="images/bird.png" alt="" />
  </div>
  <script src="common.js"></script>
  <script>
    //div摇动起来,本质是样式里面的上下,左右,移动一个随机值 Math.ramdom
    //并且在一个设定的时间区间内移动 setInterval
    //点击按钮摇起来

    my$("btn1").onclick = function () {
      timeId = setInterval(function () {
        //随机数
        var x = parseInt(Math.random() * 100 + 1);
        var y = parseInt(Math.random() * 100 + 1)
        //设置元素的left和top属性
        my$("dv").style.left = x + "px";
        my$("dv").style.top = y + "px";
      }, 100);
    };

    my$("btn2").onclick = function () {
      clearInterval(timeId);
    };
  </script>
</body>

</html>

效果:

猜你喜欢

转载自www.cnblogs.com/jane-panyiyun/p/12026494.html