网页前端后台技巧(CSS+HTML)让前端飞互联网科技

前端JavaScript-随机漂浮碰壁效果

2019-05-16  本文已影响6人  560b7bb7b879

实现了元素随机漂浮,在边缘会有触碰效果。

代码比较常见于漂浮广告,当然这种广告是不推荐使用的,让人感觉厌烦。

代码实例如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>web前端学习交流扣qun:731771211   志同道合者进</title>
<style type="text/css">
*{
  margin: 0;
  padding: 0;
  border: 0;
}
#main{
  position: absolute;
  top: 0;
  left: 0;
  cursor: pointer;
}
#img{
  width: 100px;
  height: 120px;
  background: #faa;
}
</style>
<script type="text/javascript">
window.onload = function() {
  var main = document.getElementById("main");
  sy = 0;
  speedy = 2;
  sx = 0;
  speedx = 2;
  imgh = 120;
  imgw = 100;
  winh = document.documentElement.clientHeight;
  winw = document.documentElement.clientWidth;
  function start() {
    sobj = setInterval(function() {
      sy += speedy;
      sx += speedx;
      //y轴运动
      if (sy <= 0) {
        speedy = -speedy;
      }
      if (sy >= winh - imgh) {
        speedy = -speedy;
        sy = winh - imgh;
      }
      //x轴运动
      if (sx <= 0) {
        speedx = -speedx;
      }
      if (sx >= winw - imgw) {
        speedx = -speedx;
        sx = winw - imgw;
      }
      main.style.top = sy + 'px';
      main.style.left = sx + 'px';
    }, 10)
  }
  start();
  main.onmouseover= function() {
    clearInterval(sobj);
  }
  main.onmouseout= function() {
    start();
  }
}
</script>
</head>
<body>
<div id="main">
  <div id="img"></div>
</div>
</body>
</html>

上一篇 下一篇

猜你喜欢

热点阅读