本文实例为大家分享了基于jQuery封装的拖拽事件,供大家参考,具体内容如下
HTML代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | <!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < meta http-equiv = "X-UA-Compatible" content = "ie=edge" > < script src = "jquery-3.4.1.min.js" ></ script > < script src = "Drag.js" ></ script > < title >Document</ title > < style > *{ padding: 0; margin: 0; } .box{ height: 200px; width: 200px; background-color: red; position: absolute; /* 让文字无法被选中 */ user-select:none; } </ style > </ head > < body > < div class = "box" ></ div >box</ div > < script > $('.box').Drag();//直接调用Drag()方法就可以了 </ script > </ body > </ html > |
封装的jQuery拖拽事件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | ;( function ($) { $.fn.extend({ Drag(){ //把this存起来,始终指向操作的元素 _this = this ; this .on( 'mousedown' , function (e) { //盒子距离document的距离 var positionDiv = $( this ).offset(); //鼠标点击box距离box左边的距离 var distenceX = e.pageX - positionDiv.left; //鼠标点击box距离box上边的距离 var distenceY = e.pageY - positionDiv.top; $(document).mousemove( function (e) { //盒子的x轴 var x = e.pageX - distenceX; //盒子的y轴 var y = e.pageY - distenceY; //如果盒子的x轴小于了0就让他等于0(盒子的左边界值) if (x < 0) { x = 0; } //盒子右边界值 if (x > $(document).width() - _this.outerWidth()){ x = $(document).width() - _this.outerWidth(); } //盒子的上边界值 if (y < 0) { y = 0; } //盒子的下边界值 if (y > $(document).height() - _this.outerHeight()){ y = $(document).height() - _this.outerHeight(); } //给盒子的上下边距赋值 $(_this).css({ 'left' : x, 'top' : y }); }); //在页面中当鼠标抬起的时候,就关闭盒子移动事件 $(document).mouseup( function () { $(document).off( 'mousemove' ); }); }) //把this返回回去继续使用jqurey的链式调用 return this } }) })(jQuery) |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。
- 本文固定链接: https://zxbcw.cn/post/200891/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)