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


涉及鼠标三个事件:

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>


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM