javascript实现简单的鼠标拖动效果实例


本文实例讲述了javascript实现简单的鼠标拖动效果。分享给大家供大家参考。具体分析如下:

用鼠标拖动一个元素,放到网页的任意一个位置上,这是很常见的,例如很多博客模板版块位置可以自己拖动到相应位置。

下面先写一个简单的可以实现鼠标拖动的效果。

当鼠标按下的时候,记录鼠标当前位置和元素左边距离的差值。
当鼠标移动的时候,给元素的位置赋值,就是鼠标的位置,减去刚才的差值。
当鼠标放开的时候,给鼠标移动和鼠标放开赋值null,让它们不要再有任何动作。

要点一:

disx = oevent.clientX - box.offsetLeft;

要确定拖动的时候鼠标点在元素的位置,就是鼠标位置减去元素的左边距离。

要点二:

box.style.left = oevent.clientX - disx + "px";

拖动时元素的位置,鼠标的当前位置减去前面刚计算的值。

好了,上代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>无标题文档</title>
<style>
body{margin:0; padding:0; height:1500px;}
#box{width:100px; height:100px; background:#06c; position:absolute;}
</style>
<script>
window.onload = function(){
 var box = document.getElementById("box");
 var disx =0;
 var disy = 0;
 box.onmousedown = function(evt){
 var oevent = evt || window.event;
 disx = oevent.clientX - box.offsetLeft;
 disy = oevent.clientY - box.offsetTop;
 document.onmousemove = function(evt){
  var oevent = evt || window.event;
  box.style.left = oevent.clientX - disx + "px";
  box.style.top = oevent.clientY - disy + "px";
 }
 document.onmouseup = function(){
  document.onmousemove = null;
  document.onmouseup = null;
 }
 return false;
 }
}
</script>
</head>
<body>
<h1>鼠标拖动</h1>
<div id="box"></div>
</body>
</html>

再改进一下,上面的鼠标拖动没有限制范围,有时会拖动窗口外面看不见了。下面就限制下范围

要点一:如下,如果元素的左边位置小于0时,给它赋值为0,如果大于可视窗大小减去元素本身的宽度的,给它赋值为 可视窗大小减元素本身宽度的差值。

var boxl = oevent.clientX - disx;
if(boxl < 0){
  boxl =0;
  }else if(boxl > vieww - box.offsetWidth){
  boxl = vieww - box.offsetWidth;
  }
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>无标题文档</title>
<style>
body{margin:0; padding:0;}
#box{width:100px;
height:100px;
background:#06c;
position:absolute;
}
</style>
<script>
window.onload = function(){
 var box = document.getElementById("box");
 var disx =0;
 var disy = 0;
 box.onmousedown = function(evt){
 var oevent = evt || window.event;
 disx = oevent.clientX - box.offsetLeft;
 disy = oevent.clientY - box.offsetTop;
 document.onmousemove = function(evt){
  var oevent = evt || window.event;
  var boxl = oevent.clientX - disx;
  var boxt = oevent.clientY - disy
  var vieww = document.documentElement.clientWidth || document.body.clientWidth;
  var viewh = document.documentElement.clientHeight || document.body.clientHeight;
  if(boxl < 0){
  boxl =0;
  }else if(boxl > vieww - box.offsetWidth){
  boxl = vieww - box.offsetWidth;
  }
  if(boxt < 0){
  boxt =0;
  }else if(boxt > viewh - box.offsetHeight){
  boxt = viewh- box.offsetHeight;
  }
  box.style.left = boxl + "px";
  box.style.top = boxt + "px";
 }
 document.onmouseup = function(){
  document.onmousemove = null;
  document.onmouseup = null;
 }
 return false;
 }
}
</script>
</head>
<body>
<h1>鼠标拖动</h1>
<div id="box"></div>
</body>
</html>

希望本文所述对大家的javascript程序设计有所帮助。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3