码迷,mamicode.com
首页 > 移动开发 > 详细

javascript -- (点击div,随鼠标移动)

时间:2016-08-11 21:01:51      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:

涉及鼠标三个事件:

onmousedown、onmousemove、onmouseup

<script type = "text/javascript">

  var body = document.getElementsByTagName(‘body‘)[0];

  //生成div,并设置其样式

  var box = document.createElement(‘div‘);

  box.style.width = ‘100px‘;

  box.style.height = ‘100px‘;

  box.style.background = ‘blue‘;

  box.style.position = ‘absolute‘;

  box.onmousedown = function(event) {

    event = event || window.event;

    //获取鼠标点击的位置距离div左边的距离

    var positionX = event.clientX - box.offsetLeft;

    var positionY = event.clientY - box.offsetTop;

    document.onmousemove = function(event) {

       event = event || window.event;??

       var divX = event.clientX - positionX;

       var divY = event.clientY - positionY;

       box.style.left = divX + ‘px‘;

       box.style.top = divY + ‘px‘;

    }

    document.onmouseup = function() {

       document.onmousemove = null;

    }?  

  }

  body.appendChild(box);

</script>

javascript -- (点击div,随鼠标移动)

标签:

原文地址:http://www.cnblogs.com/zhao12354/p/5762406.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!