很多时候我们做网站都会遇到 JS拖拽的需求,今天就按照一个弹出框拖拽作为一个小案例写个JS原生的代码。
按照上面的需求咱们开始制作一个拖拽效果吧。
第一步、咱们得写一个布局和响应的css
<div id="box">
<div id="btn">标题</div>
<p>青格勒前端博客!</p>
<p>www.cenggel.com</p></div>
<style>
#box{ height:200px; width:200px; background:#999; position:absolute;} #btn{ height:30px; background:#000; cursor:all-scroll; padding:0 10px; color:#fff;}</style>
这里的话咱们id=btn的为拖拽的区域。
二、逻辑讲述
整个JS代码不是很多,当鼠标按下的时候获取鼠标的位置和id=box的上距和左边距,然后计算目前的位置。
然后这时候鼠标移动的时候再次计算鼠标的位置,然后给id=box位置
当鼠标按钮松开的时候把onmousemove和onmouseup清除掉
三、JS代码部分
<script type="text/javascript">
function drag(obtnf,obtn){ //按钮及初始值
var obtn = document.getElementById(obtn),
obtnf = document.getElementById(obtnf),
disX = 0,
disY = 0; //鼠标按下时开始计算
obtn.onmousedown = function(ev){ var ev = ev || window.event;
disX = ev.clientX - obtnf.offsetLeft;
disY = ev.clientY - obtnf.offsetTop; //鼠标按下并移动时计算
document.onmousemove = function(ev){ var ev = ev || window.event;
obtnf.style.left = ev.clientX - disX + 'px';
obtnf.style.top = ev.clientY - disY + 'px';
}; //鼠标松开时清除时间
document.onmouseup = function(){ document.onmousemove = null; document.onmouseup = null;
}; return false;
};
}; //引用
drag("box","btn")</script> www.gendan5.com
最后咱们的效果如下
做到这里其实咱们的效果并不完美,应为当我们拖拽的时候发现,他能直接被拖到浏览器的外面去了,所以咱们再给他加点限制。
最终JS代码如下:
<script type="text/javascript">
function xianzhi(val,max,min){ if (val > max){ return max;
}else if(val < min){ return min;
}else{ return val;
} console.log(val)
} function drag(obtnf,obtn){ //按钮及初始值
var obtn = document.getElementById(obtn),
obtnf = document.getElementById(obtnf),
disX = 0,
disY = 0; //鼠标按下时开始计算
obtn.onmousedown = function(ev){ var ev = ev || window.event;
disX = ev.clientX - obtnf.offsetLeft;
disY = ev.clientY - obtnf.offsetTop; //鼠标按下并移动时计算
document.onmousemove = function(ev){ var ev = ev || window.event; var lefts= (ev.clientX - disX),
tops= (ev.clientY - disY),
maxle= (document.documentElement.clientWidth - obtnf.offsetWidth),
maxto= (document.documentElement.clientHeight - obtnf.offsetHeight)
lefts = xianzhi(lefts,maxle,0)
tops = xianzhi(tops,maxto,0)
obtnf.style.left = lefts + 'px';
obtnf.style.top = tops + 'px';
}; //鼠标松开时清除时间
document.onmouseup = function(){ document.onmousemove = null; document.onmouseup = null;
}; return false;
};
}; //引用
drag("box","btn")
做到这里一个小型的拖拽效果就出来了。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:http://blog.itpub.net/69946337/viewspace-2657652/