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