JSBom联合Dom的应用

世界未亡 死不投降 大家好我们又见面了,为了弥补上周为完成的任务,继续奋战啊为了大家。而这次我为大家带来的是一份联合了Bom以及Dom的一个小的代码效果

  <!DOCTYPE html>
  <html>
  <head lang="en">
  <meta charset="UTF-8">
  <title></title>
  <style>
  body{margin: 0;}
  #div1{
  width: 50px;
  height: 50px;
  background-color: red;
  position: absolute;
  /*left: 100px;*/
  }
  </style>
  </head>
  <body>
  <button onclick="mymove()">移动</button>
   
  <button onclick="myinfo()">界面</button>
  <hr/>
  <div id="div1"></div>
   
  <script>
  function myinfo(){
  alert(window.document.body.offsetWidth);
  }
  var num = 2;
  function mymove(){
  var div1 = document.getElementById('div1');
  // alert(div1.offsetLeft+',,'+div1.offsetTop);
  // 元素没有被设置的样式属性相当于不存在
  // 样式属性写在style标记当中,但是使用dom方式无法直接通过style属性来读取
  // 通过元素的style属性而能够获取的样式值必须是写在元素内部的
  // alert(div1.style.left);
   
  div1.style.left = div1.offsetLeft + num + "px";
  if(div1.offsetLeft+div1.offsetWidth>=document.body.offsetWidth
  || div1.offsetLeft<= 0)
  num = -num;
   
  window.setTimeout(mymove, 50);
   
  }
  </script>
  </body>
  </html>

      这次的代码看起来是很有趣的,是一个很小的div方块在网页中不停的移动,可以将其看作一个小的flash效果,完成后还是有点小小的自豪吧,哈哈。

 

posted @ 2017-03-18 10:26  Nevr  阅读(133)  评论(0编辑  收藏  举报