赵工的个人空间


网络课堂部分转网页计算部分转编程演练

 JS使用技巧

首页 > 网络课堂 > JS使用技巧 > 鼠标拖动div的方法
鼠标拖动div的方法

如果需要使用鼠标来拖动div,这个div的css样式的position属性必须设置为absolute,css中一般还需要设置初始的位置,即属性left和top,为了使此div位于其他页面元素上面,需要设置z-index属性值大于其他页面元素。示例:

#divdrag {
  position: absolute;
  width: 300px;
  height: 300px;
  z-index: 2;
  left: 20px;
  top: 500px;
  cursor:move;
}

其中还设置了cursor属性,当鼠标移动到此div上时光标变为'move'样式,显示为四面有箭头。示例中使用的是id选择器,也就是只设置了一个可移动div,也可以使用class,设置多个div可拖动。然后就可以使用JavaScript处理拖动了:

document.getElementById('divdrag').onmousedown=function(){
  var divdrag=document.getElementById("divdrag");
  divdrag.style.cursor="pointer";
  document.onmousemove=function(){
    var x=event.clientX;
    var y=event.clientY;
    divdrag.style.left=(x-100)+'px';
    divdrag.style.top=(y-100)+'px';
  }
}
document.getElementById("divdrag").onmouseup=function(){
  document.onmousemove=false;
}

更常用的是使用jQuery来操作div,示例代码:

$("#divdrag").mousedown(function(e){
  var flag=true;
  var xpos=e.pageX-parseInt($("#divdrag").css("left"));
  var ypos=e.pageY-parseInt($("#divdrag").css("top"));
  $("#divdrag").fadeTo(20, 0.5);//点击后开始拖动并透明显示
  $(document).mousemove(function(e){
    if(flag){
      var x=e.pageX-xpos;//移动时根据鼠标位置计算控件左上角的绝对位置
      var y=e.pageY-ypos;
      $("#divdrag").css({top:y,left:x});//控件新位置
    }
  }).mouseup(function(){
    flag=false;
    $("#divdrag").fadeTo("fast", 1);//松开鼠标后停止移动并恢复成不透明
  });
});
Copyright@dwenzhao.cn All Rights Reserved   备案号:粤ICP备15026949号
联系邮箱:dwenzhao@163.com  QQ:1608288659