zoukankan      html  css  js  c++  java
  • 创建一个可拖动的dom元素。

    首先先建立一个div。

    1 var elem = document.createElement('div');
    2 elem.style.height = '100px';
    3 elem.style.width = '100px';
    4 elem.style.backgroundColor = '#ff0';
    5 document.body.appendChild(elem);

    给元素附加onmousedown事件,这个onmousedown事件又会触发document的onmousemove事件,document的时间用来捕捉到鼠标的坐标,然后把坐标赋给elem的left和top。元素onmouseup事件会把document的onmousemove事件清空(通过赋值为null)。所以元素会停留在松开鼠标的位置。

     1 elem.onmousedown = function (){
     2   this.style.position = 'absolute';
     3    document.onmousemove = function (e){
     4      elem.style.left = e.pageX - parseInt(elem.style.width)/2;
     5      elem.style.top = e.pageY - parseInt(elem.style.height)/2;
     6       }
     7    }
     8 document.onmouseup = function (){
     9   document.onmousemove = null;
    10   }
  • 相关阅读:
    c# 进制
    java生成验证码
    java基础练习题
    java九九乘法表
    java list集合练习
    深入理解Java的接口和抽象类
    java 接口 练习
    java泛型详解
    Java 继承 小练习
    Java单例模式深入详解
  • 原文地址:https://www.cnblogs.com/SKLthegoodman/p/3509974.html
Copyright © 2011-2022 走看看