JavaScript实现的多种鼠标拖放效果


Posted in Javascript onNovember 03, 2015

本文实例讲述了JavaScript实现的多种鼠标拖放效果。分享给大家供大家参考,具体如下:

这是一款JavaScript鼠标拖放效果代码,通过本示例了解触发对象,设置范围限制,指定容器大小水平及垂直锁定,还包括获取和释放焦点等。

运行效果截图如下:

JavaScript实现的多种鼠标拖放效果

在线演示地址如下:

具体代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>拖放效果</title>
</head>
<body>
<script> 
var isIE = (document.all) ? true : false;
var $ = function (id) {
 return "string" == typeof id ? document.getElementById(id) : id;
};
var Class = {
 create: function() {
  return function() { this.initialize.apply(this, arguments); }
 }
}
var Extend = function(destination, source) {
 for (var property in source) {
  destination[property] = source[property];
 }
}
var Bind = function(object, fun) {
 return function() {
  return fun.apply(object, arguments);
 }
}
var BindAsEventListener = function(object, fun) {
 return function(event) {
  return fun.call(object, (event || window.event));
 }
}
var CurrentStyle = function(element){
 return element.currentStyle || document.defaultView.getComputedStyle(element, null);
}
function addEventHandler(oTarget, sEventType, fnHandler) {
 if (oTarget.addEventListener) {
  oTarget.addEventListener(sEventType, fnHandler, false);
 } else if (oTarget.attachEvent) {
  oTarget.attachEvent("on" + sEventType, fnHandler);
 } else {
  oTarget["on" + sEventType] = fnHandler;
 }
};
function removeEventHandler(oTarget, sEventType, fnHandler) {
 if (oTarget.removeEventListener) {
 oTarget.removeEventListener(sEventType, fnHandler, false);
 } else if (oTarget.detachEvent) {
 oTarget.detachEvent("on" + sEventType, fnHandler);
 } else { 
 oTarget["on" + sEventType] = null;
 }
};
//拖放程序
var Drag = Class.create();
Drag.prototype = {
//拖放对象
 initialize: function(drag, options) {
 this.Drag = $(drag);//拖放对象
 this._x = this._y = 0;//记录鼠标相对拖放对象的位置
 this._marginLeft = this._marginTop = 0;//记录margin
 //事件对象(用于绑定移除事件)
 this._fM = BindAsEventListener(this, this.Move);
 this._fS = Bind(this, this.Stop);
 this.SetOptions(options);
 this.Limit = !!this.options.Limit;
 this.mxLeft = parseInt(this.options.mxLeft);
 this.mxRight = parseInt(this.options.mxRight);
 this.mxTop = parseInt(this.options.mxTop);
 this.mxBottom = parseInt(this.options.mxBottom);
 this.LockX = !!this.options.LockX;
 this.LockY = !!this.options.LockY;
 this.Lock = !!this.options.Lock;
 this.onStart = this.options.onStart;
 this.onMove = this.options.onMove;
 this.onStop = this.options.onStop;
 this._Handle = $(this.options.Handle) || this.Drag;
 this._mxContainer = $(this.options.mxContainer) || null;
 this.Drag.style.position = "absolute";
 //透明
 if(isIE && !!this.options.Transparent){
  //填充拖放对象
  with(this._Handle.appendChild(document.createElement("div")).style){
   width = height = "100%"; backgroundColor = "#fff"; filter = "alpha(opacity:0)";
  }
 }
 //修正范围
 this.Repair();
 addEventHandler(this._Handle, "mousedown", BindAsEventListener(this, this.Start));
 },
 //设置默认属性
 SetOptions: function(options) {
 this.options = {//默认值
  Handle:   "",//设置触发对象(不设置则使用拖放对象)
  Limit:   false,//是否设置范围限制(为true时下面参数有用,可以是负数)
  mxLeft:   0,//左边限制
  mxRight:  9999,//右边限制
  mxTop:   0,//上边限制
  mxBottom:  9999,//下边限制
  mxContainer: "",//指定限制在容器内
  LockX:   false,//是否锁定水平方向拖放
  LockY:   false,//是否锁定垂直方向拖放
  Lock:   false,//是否锁定
  Transparent: false,//是否透明
  onStart:  function(){},//开始移动时执行
  onMove:   function(){},//移动时执行
  onStop:   function(){}//结束移动时执行
 };
 Extend(this.options, options || {});
 },
 //准备拖动
 Start: function(oEvent) {
 if(this.Lock){ return; }
 this.Repair();
 //记录鼠标相对拖放对象的位置
 this._x = oEvent.clientX - this.Drag.offsetLeft;
 this._y = oEvent.clientY - this.Drag.offsetTop;
 //记录margin
 this._marginLeft = parseInt(CurrentStyle(this.Drag).marginLeft) || 0;
 this._marginTop = parseInt(CurrentStyle(this.Drag).marginTop) || 0;
 //mousemove时移动 mouseup时停止
 addEventHandler(document, "mousemove", this._fM);
 addEventHandler(document, "mouseup", this._fS);
 if(isIE){
  //焦点丢失
  addEventHandler(this._Handle, "losecapture", this._fS);
  //设置鼠标捕获
  this._Handle.setCapture();
 }else{
  //焦点丢失
  addEventHandler(window, "blur", this._fS);
  //阻止默认动作
  oEvent.preventDefault();
 };
 //附加程序
 this.onStart();
 },
 //修正范围
 Repair: function() {
 if(this.Limit){
  //修正错误范围参数
  this.mxRight = Math.max(this.mxRight, this.mxLeft + this.Drag.offsetWidth);
  this.mxBottom = Math.max(this.mxBottom, this.mxTop + this.Drag.offsetHeight);
  //如果有容器必须设置position为relative来相对定位,并在获取offset之前设置
  !this._mxContainer || CurrentStyle(this._mxContainer).position == "relative" || (this._mxContainer.style.position = "relative");
 }
 },
 //拖动
 Move: function(oEvent) {
 //判断是否锁定
 if(this.Lock){ this.Stop(); return; };
 //清除选择
 window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
 //设置移动参数
 var iLeft = oEvent.clientX - this._x, iTop = oEvent.clientY - this._y;
 //设置范围限制
 if(this.Limit){
  //设置范围参数
  var mxLeft = this.mxLeft, mxRight = this.mxRight, mxTop = this.mxTop, mxBottom = this.mxBottom;
  //如果设置了容器,再修正范围参数
  if(!!this._mxContainer){
   mxLeft = Math.max(mxLeft, 0);
   mxTop = Math.max(mxTop, 0);
   mxRight = Math.min(mxRight, this._mxContainer.clientWidth);
   mxBottom = Math.min(mxBottom, this._mxContainer.clientHeight);
  };
  //修正移动参数
  iLeft = Math.max(Math.min(iLeft, mxRight - this.Drag.offsetWidth), mxLeft);
  iTop = Math.max(Math.min(iTop, mxBottom - this.Drag.offsetHeight), mxTop);
 }
 //设置位置,并修正margin
 if(!this.LockX){ this.Drag.style.left = iLeft - this._marginLeft + "px"; }
 if(!this.LockY){ this.Drag.style.top = iTop - this._marginTop + "px"; }
 //附加程序
 this.onMove();
 },
 //停止拖动
 Stop: function() {
 //移除事件
 removeEventHandler(document, "mousemove", this._fM);
 removeEventHandler(document, "mouseup", this._fS);
 if(isIE){
  removeEventHandler(this._Handle, "losecapture", this._fS);
  this._Handle.releaseCapture();
 }else{
  removeEventHandler(window, "blur", this._fS);
 };
 //附加程序
 this.onStop();
 }
};
</script>
<style> 
#idContainer{ border:10px solid #990000; width:600px; height:300px;}
#idDrag{ border:5px solid #C4E3FD; background:#C4E3FD; width:50px; height:50px; top:50px; left:50px;}
#idHandle{cursor:move; height:25px; background:#0000FF; overflow:hidden;}
</style>
<div id="idContainer">
<div id="idDrag"><div id="idHandle"></div></div>
</div>
<input id="idReset" type="button" value="复位" />
<input id="idLock" type="button" value="锁定" />
<input id="idLockX" type="button" value="锁定水平" />
<input id="idLockY" type="button" value="锁定垂直" />
<input id="idLimit" type="button" value="范围锁定" />
<input id="idLimitOff" type="button" value="取消范围锁定" />
<br />拖放状态:<span id="idShow">未开始</span>
<script> 
var drag = new Drag("idDrag", { mxContainer: "idContainer", Handle: "idHandle", Limit: true,
 onStart: function(){ $("idShow").innerHTML = "开始拖放"; },
 onMove: function(){ $("idShow").innerHTML = "left:"+this.Drag.offsetLeft+";top:"+this.Drag.offsetTop; },
 onStop: function(){ $("idShow").innerHTML = "结束拖放"; }
});
$("idReset").onclick = function(){
 drag.Limit = true;
 drag.mxLeft = drag.mxTop = 0;
 drag.mxRight = drag.mxBottom = 9999;
 drag.LockX = drag.LockY = drag.Lock = false;
}
$("idLock").onclick = function(){ drag.Lock = true; }
$("idLockX").onclick = function(){ drag.LockX = true; }
$("idLockY").onclick = function(){ drag.LockY = true; }
$("idLimit").onclick = function(){  drag.mxRight = drag.mxBottom = 200;drag.Limit = true; }
$("idLimitOff").onclick = function(){ drag.Limit = false; }
</script>
</body>
</html>

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

Javascript 相关文章推荐
jQuery实现div浮动层跟随页面滚动效果
Feb 11 Javascript
jquery实现带二级菜单的导航示例
Apr 28 Javascript
用js一次改变多个input的readonly属性值的方法
Jun 11 Javascript
JavaScript中使用stopPropagation函数停止事件传播例子
Aug 27 Javascript
JavaScript调试工具汇总
Dec 23 Javascript
JS基于面向对象实现的放烟花效果
May 07 Javascript
js判断浏览器类型及设备(移动页面开发)
Jul 30 Javascript
jquery插件jquery.beforeafter.js实现左右拖拽分隔条对比图片的方法
Aug 07 Javascript
jQuery常用知识点总结以及平时封装常用函数
Feb 23 Javascript
js 获取元素所有兄弟节点的实现方法
Sep 06 Javascript
jQuery读取本地的json文件(实例讲解)
Oct 31 jQuery
通过JS运行机制的角度说说作用域
Mar 12 Javascript
JavaScript实现的Tween算法及缓冲特效实例代码
Nov 03 #Javascript
jQuery实现Email邮箱地址自动补全功能代码
Nov 03 #Javascript
jQuery实现仿QQ头像闪烁效果的文字闪动提示代码
Nov 03 #Javascript
基于JavaScript怎么实现让歌词滚动播放
Nov 03 #Javascript
ECMA5数组的新增方法有哪些及forEach()模仿实现
Nov 03 #Javascript
Javascript设计模式理论与编程实战之简单工厂模式
Nov 03 #Javascript
JS实现网页标题随机显示名人名言的方法
Nov 03 #Javascript
You might like
php预定义变量使用帮助(带实例)
2013/10/30 PHP
两千行代码的PHP学习笔记汇总
2014/10/05 PHP
php文件上传简单实现方法
2015/01/24 PHP
PHP中让json_encode不自动转义斜杠“/”的方法
2017/02/28 PHP
PHP5.6新增加的可变函数参数用法分析
2017/08/25 PHP
thinkphp 框架数据库切换实现方法分析
2020/05/18 PHP
判断控件是否已加载完成的代码
2010/02/24 Javascript
JS对文本框值的判断示例
2014/03/10 Javascript
js获得网页背景色和字体色的方法
2014/03/21 Javascript
Window.Open如何在同一个标签页打开
2014/06/20 Javascript
jquery实现像栅栏一样左右滑出式二级菜单效果代码
2015/08/24 Javascript
js实现仿qq消息的弹出窗效果
2016/01/06 Javascript
Highcharts学习之坐标轴
2016/08/02 Javascript
node.js连接MongoDB数据库的2种方法教程
2017/05/17 Javascript
JavaScript对象原型链原理解析
2020/01/22 Javascript
vue+ts下对axios的封装实现
2020/02/18 Javascript
[01:03:36]Ti4 循环赛第三日DK vs Titan
2014/07/12 DOTA
Python-嵌套列表list的全面解析
2016/06/08 Python
Python3操作SQL Server数据库(实例讲解)
2017/10/21 Python
python基于twisted框架编写简单聊天室
2018/01/02 Python
python实现Decorator模式实例代码
2018/02/09 Python
python使用numpy读取、保存txt数据的实例
2018/10/14 Python
Python3对称加密算法AES、DES3实例详解
2018/12/06 Python
python爬虫 2019中国好声音评论爬取过程解析
2019/08/26 Python
Python3.7基于hashlib和Crypto实现加签验签功能(实例代码)
2019/12/04 Python
python使用多线程+socket实现端口扫描
2020/05/28 Python
基于Python快速处理PDF表格数据
2020/06/03 Python
Python虚拟环境的创建和使用详解
2020/09/07 Python
Manjaro、pip、conda更换国内源的方法
2020/11/17 Python
HTML5制作表格样式
2016/11/15 HTML / CSS
五年后的职业生涯规划
2014/03/04 职场文书
2014年物业公司工作总结
2014/11/22 职场文书
详解如何在Canvas中添加事件的方法
2021/04/17 Javascript
Python数据类型最全知识总结
2021/05/31 Python
科学家研发出新型速效酶,可在 24 小时内降解塑料制品
2022/04/29 数码科技
Python代码实现双链表
2022/05/25 Python