JavaScript-纯javascript实现一个拖拽效果的程序
千万不要贴jq的哦,
最好是性能好点的
大致可以实现一下几点:
任意方向 水平方向 垂直方向 停止拖拽 开启拖拽 恢复初始状态
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
千万不要贴jq的哦,
最好是性能好点的
大致可以实现一下几点:
任意方向 水平方向 垂直方向 停止拖拽 开启拖拽 恢复初始状态
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(7)
我也分享一个
<!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">
<!-- DW6 -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>shawl.qiu template</title>
<script type="text/javascript">
//<![CDATA[
function fDragging(obj, e, limit){
if(!e) e=window.event;
var x=parseInt(obj.style.left);
var y=parseInt(obj.style.top);
var x_=e.clientX-x;
var y_=e.clientY-y;
if(document.addEventListener){
document.addEventListener('mousemove', inFmove, true);
document.addEventListener('mouseup', inFup, true);
} else if(document.attachEvent){
document.attachEvent('onmousemove', inFmove);
document.attachEvent('onmouseup', inFup);
}
inFstop(e);
inFabort(e)
function inFmove(e){
var evt;
if(!e)e=window.event;
if(limit){
var op=obj.parentNode;
var opX=parseInt(op.style.left);
var opY=parseInt(op.style.top);
if((e.clientX-x_)<0) return false;
else if((e.clientX-x_+obj.offsetWidth+opX)>(opX+op.offsetWidth)) return false;
if(e.clientY-y_<0) return false;
else if((e.clientY-y_+obj.offsetHeight+opY)>(opY+op.offsetHeight)) return false;
//status=e.clientY-y_;
}
obj.style.left=e.clientX-x_+'px';
obj.style.top=e.clientY-y_+'px';
inFstop(e);
} // shawl.qiu script
function inFup(e){
var evt;
if(!e)e=window.event;
if(document.removeEventListener){
document.removeEventListener('mousemove', inFmove, true);
document.removeEventListener('mouseup', inFup, true);
} else if(document.detachEvent){
document.detachEvent('onmousemove', inFmove);
document.detachEvent('onmouseup', inFup);
}
inFstop(e);
} // shawl.qiu script
function inFstop(e){
if(e.stopPropagation) return e.stopPropagation();
else return e.cancelBubble=true;
} // shawl.qiu script
function inFabort(e){
if(e.preventDefault) return e.preventDefault();
else return e.returnValue=false;
} // shawl.qiu script
}
//]]>
</script>
</head>
<body>
<div style=" border:1px dashed blue; width: 760px; height:600px; text-align:center; position:absolute; left:100px; top: 10px;"> this parent
<div style=" border:1px dashed blue; width: 180px; text-align:center; position:absolute; left:50px; top: 50px;" onmousedown="fDragging(this, event, true);">
element <br/>
dragging compatibility for IE, Opera, Firefox.
</div>
<div style=" border:1px dashed blue; width: 180px; text-align:center; position:absolute; left:100px; top: 150px;" onmousedown="fDragging(this, event, true);">
element 1<br/>
dragging compatibility for IE, Opera, Firefox.
</div>
<div style=" border:1px dashed blue; width: 180px; text-align:center; position:absolute; left:200px; top: 250px;" onmousedown="fDragging(this, event, false);">
element 2<br/>
dragging compatibility for IE, Opera, Firefox. <br/>
<font color="red">dragging everywhere</font>
</div>
</div>
</body>
</html>
<script type="text/javascript">
var dragging = false;
var test;
var mouseY;
var mouseX;
window.onload = function(){
test = document.getElementById("test");
test.onmousedown = down;
test.onmousemove = move;
document.onmouseup = up;
test.style.position = "relative";
test.style.top = "0px";
test.style.left = "0px";
}
function down(event)
{
event = event || window.event;
dragging = true;
mouseX = parseInt(event.clientX);
mouseY = parseInt(event.clientY);
objY = parseInt(test.style.top);
objX = parseInt(test.style.left);
}
function move(event){
event = event || window.event;
if(dragging == true){
var x,y;
y = event.clientY - mouseY + objY;
x = event.clientX - mouseX + objX;
test.style.top = y + "px";
test.style.left = x + "px";
}
}
function up(){
dragging = false;
}
</script>
<div id="test" style="border:1px solid; width:400px; background:#CCCCCC;">
<p>我是拖拽示例DIV。</p>
<p>可以试验一下效果。</p>
</div>
推荐一个,使用非常方便:
<div id="box">
<div id="main">
<div id="bar">拖拽</div>
<div id="content">
内容……
</div>
</div>
</div>
<style type="text/css">
#box{position:absolute; left:100px; top:100px; padding:5px; background:#f0f3f9; font-size:12px; -moz-box-shadow:2px 2px 4px #666666; -webkit-box-shadow:2px 2px 4px #666666;}
#main{border:1px solid #a0b3d6; background:white;}
#bar{line-height:24px; background:#beceeb; border-bottom:1px solid #a0b3d6; padding-left:5px; cursor:move;}
#content{width:420px; height:250px; padding:10px 5px;}
</style>
<SCRIPT LANGUAGE="JavaScript">
<!--
var params = {
left: 0,
top: 0,
currentX: 0,
currentY: 0,
flag: false
};
//获取相关CSS属性
var getCss = function(o,key){
return o.currentStyle? o.currentStyle[key] : document.defaultView.getComputedStyle(o,false)[key];
};
//拖拽的实现
var startDrag = function(bar, target){
if(getCss(target, "left") !== "auto"){
params.left = getCss(target, "left");
}
if(getCss(target, "top") !== "auto"){
params.top = getCss(target, "top");
}
//o是移动对象
bar.onmousedown = function(event){
params.flag = true;
if(!event){
event = window.event;
//防止IE文字选中
bar.onselectstart = function(){
return false;
}
}
var e = event;
params.currentX = e.clientX;
params.currentY = e.clientY;
};
document.onmouseup = function(){
params.flag = false;
if(getCss(target, "left") !== "auto"){
params.left = getCss(target, "left");
}
if(getCss(target, "top") !== "auto"){
params.top = getCss(target, "top");
}
};
document.onmousemove = function(event){
var e = event ? event: window.event;
if(params.flag){
var nowX = e.clientX, nowY = e.clientY;
var disX = nowX - params.currentX, disY = nowY - params.currentY;
target.style.left = parseInt(params.left) + disX + "px";
target.style.top = parseInt(params.top) + disY + "px";
}
}
};
var oBox = document.getElementById("box");
var oBar = document.getElementById("bar");
startDrag(oBar, oBox);
//-->
</SCRIPT>
<html>
<head><title>拖动效果函数演示</title>
<style>
body{
font-size:12px;
color:#333333;
border : 0px solid blue;
}
div{
position : absolute;
background-color : #c3d9ff;
margin : 0px;
padding : 5px;
border : 0px;
width : 100px;
height:100px;
}
</style>
</head>
<body>
<script>
window.onload = function(){
drag("div1");
}
function drag(o,s) {
if (typeof o == "string") o = document.getElementById(o);
o.orig_x = parseInt(o.style.left) - document.body.scrollLeft;
o.orig_y = parseInt(o.style.top) - document.body.scrollTop;
o.orig_index = o.style.zIndex;
o.onmousedown = function(a){
this.style.cursor = "move";
this.style.zIndex = 10000;
var d=document;
if(!a)a=window.event;
var x = a.clientX+d.body.scrollLeft-o.offsetLeft;
var y = a.clientY+d.body.scrollTop-o.offsetTop;
d.ondragstart = "return false;"
d.onselectstart = "return false;"
d.onselect = "document.selection.empty();"
if(o.setCapture)
o.setCapture();
else if(window.captureEvents)
window.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP);
d.onmousemove = function(a){
if(!a)a=window.event;
o.style.left = a.clientX+document.body.scrollLeft-x;
o.style.top = a.clientY+document.body.scrollTop-y;
o.orig_x = parseInt(o.style.left) - document.body.scrollLeft;
o.orig_y = parseInt(o.style.top) - document.body.scrollTop;
}
d.onmouseup = function(){
if(o.releaseCapture)
o.releaseCapture();
else if(window.captureEvents)
window.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP);
d.onmousemove = null;
d.onmouseup = null;
d.ondragstart = null;
d.onselectstart = null;
d.onselect = null;
o.style.cursor = "normal";
o.style.zIndex = o.orig_index;
}
}
if (s) {
var orig_scroll = window.onscroll?window.onscroll:function (){};
window.onscroll = function (){
orig_scroll();
o.style.left = o.orig_x + document.body.scrollLeft;
o.style.top = o.orig_y + document.body.scrollTop;
}
}
}
</script>
<div id="div1" style="left:230px;top:120px;background-color : #e3f944;width:200px;">参数说明:
drag(obj [,scroll]);
obj:对象的id或对象本身;
scroll(可选):对象是否随窗口拖动而滑动,默认为否
鼠标右键查看源代码
</div>
</body>
分享一个,可以实现任意方向的拖动与停靠,实现效果:
<!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)"; fontSize = 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或absolute来相对或绝对定位,并在获取offset之前设置
!this._mxContainer || CurrentStyle(this._mxContainer).position == "relative" || CurrentStyle(this._mxContainer).position == "absolute" || (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>
这个很好哦,这是我以前收藏的,分享给你...
<script type="text/javascript">
/**
*
* 基本拖拽
* new Dragdrop({
* target 拖拽元素 HTMLElemnt 必选
* bridge 指定鼠标按下哪个元素时开始拖拽,实现模态对话框时用到
* dragable 是否可拖拽 (true)默认
* dragX true/false false水平方向不可拖拽 (true)默认
* dragY true/false false垂直方向不可拖拽 (true)默认
* area [minX,maxX,minY,maxY] 指定拖拽范围 默认任意拖动
* callback 移动过程中的回调函数
* });
*
* demo
*/
Dragdrop = function(window){
var doc = window.document;
var E = {
on : function(el, type, fn){
el.addEventListener ?
el.addEventListener(type, fn, false) :
el.attachEvent ?
el.attachEvent("on" + type, fn) :
el['on'+type] = fn;
},
un : function(el,type,fn){
el.removeEventListener ?
el.removeEventListener(type, fn, false) :
el.detachEvent ?
el.detachEvent("on" + type, fn) :
el['on'+type] = null;
},
evt : function(e){
return e || window.event;
}
};
return function(opt){
var conf = null, defaultConf, diffX, diffY;
function Config(opt){
this.target = opt.target;
this.bridge = opt.bridge;
this.dragable = opt.dragable != false;
this.dragX = opt.dragX != false;
this.dragY = opt.dragY != false;
this.area = opt.area;
this.callback = opt.callback;
}
function Dragdrop(opt){
if(!opt){return;}
conf = new Config(opt);
defaultConf = new Config(opt);
conf.bridge ?
E.on(conf.bridge,'mousedown',mousedown) :
E.on(conf.target,'mousedown',mousedown);
}
Dragdrop.prototype = {
dragX : function(){
conf.dragX = true;
conf.dragY = false;
},
dragY : function(b){
conf.dragY = true;
conf.dragX = false;
},
dragAll : function(){
conf.dragX = true;
conf.dragY = true;
},
setArea : function(a){
conf.area = a;
},
setBridge : function(b){
conf.bridge = b;
},
setDragable : function(b){
conf.dragable = b;
},
reStore : function(){
conf = new Config(defaultConf);
conf.target.style.top = '0px';
conf.target.style.left = '0px';
},
getDragX : function(){
return conf.dragX;
},
getDragY : function(){
return conf.dragY;
}
}
function mousedown(e){
e = E.evt(e);
var el = conf.target;
el.style.position = 'absolute';
el.style.cursor = 'move';
if(el.setCapture){ //IE
E.on(el, "losecapture", mouseup);
el.setCapture();
e.cancelBubble = true;
}else if(window.captureEvents){ //标准DOM
e.stopPropagation();
E.on(window, "blur", mouseup);
e.preventDefault();
}
diffX = e.clientX - el.offsetLeft;
diffY = e.clientY - el.offsetTop;
E.on(doc,'mousemove',mousemove);
E.on(doc,'mouseup',mouseup);
}
function mousemove(e){
var el = conf.target, e = E.evt(e), moveX = e.clientX - diffX, moveY = e.clientY - diffY;
var minX, maxX, minY, maxY;
if(conf.area){
minX = conf.area[0];
maxX = conf.area[1];
minY = conf.area[2];
maxY = conf.area[3];
moveX < minX && (moveX = minX); // left 最小值
moveX > maxX && (moveX = maxX); // left 最大值
moveY < minY && (moveY = minY); // top 最小值
moveY > maxY && (moveY = maxY); // top 最大值
}
if(conf.dragable){
conf.dragX && (el.style.left = moveX + 'px');
conf.dragY && (el.style.top = moveY + 'px');
if(conf.callback){
var obj = {moveX:moveX,moveY:moveY};
conf.callback.call(conf,obj);
}
}
}
function mouseup(e){
var el = conf.target;
el.style.cursor = 'default';
E.un(doc,'mousemove',mousemove);
E.un(doc,'mouseup',mouseup);
if(el.releaseCapture){ //IE
E.un(el, "losecapture", mouseup);
el.releaseCapture();
}
if(window.releaseEvents){ //标准DOM
E.un(window, "blur", mouseup);
}
}
return new Dragdrop(opt);
}
}(this);
</script>
我这边有几个网站,供大家参考~
http://bbs.blueidea.com/thread-2896954-1-1.html
http://www.itokit.com/2011/0604/66380.html
http://www.gzzsnet.com/js/5613.html
http://www.xiaolanhu.com/content.asp?cla_id=5&id=116