jquery 实现简单拖拽

基本思路:1.首先需要鼠标按下拖动区域,也就是需要调用 mousedown 方法

                 2.鼠标移动,需要拖动的元素跟着鼠标移动,调用 mousemove 方法

                 3.鼠标弹起拖动消失,调用 mouseup 方法

下面看一下代码:

页面结构:

 样式:

.drag {
    width: 200px;
    height: 200px;
    background-color: skyblue;
    position: absolute;
}

效果图:

逻辑代码:

// 拖拽函数
function function_drag(ele) {
	$(ele).mousedown(function(e){
		// 获取鼠标离元素(0,0)位置的距离
		var positionDiv = $(this).offset(); //offset 元素的偏移坐标 有两个属性:top  left(对显示的元素有用)
		var distenceX = e.pageX - positionDiv.left; //page  显示鼠标指针的位置   (此时相当于,鼠标按下的初始值)
		var distenceY = e.pageY - positionDiv.top; //

		// 鼠标移动
		$(document).mousemove(function(e){
			// 获取鼠标的位移(鼠标此时的page值 - 鼠标按下时的初始值 = 元素的移动值)
			var x = e.pageX - distenceX;
			var y = e.pageY - distenceY;
			if(x<0){
				x=0;
			}else if(x>$(document).width()-$(ele).outerWidth(true)){
				x = $(document).width()-$(ele).outerWidth(true);
			}
			if(y<0){
			  y=0;
			}else if(y>$(document).height()-$(ele).outerHeight(true)){
			  y = $(document).height()-$(ele).outerHeight(true);
			}
			$(ele).css({
				'left':x+'px',
				'top':y+'px'
			})
		})

		// 鼠标抬起
		$(document).mouseup(function(e){
			$(document).off('mousemove');
		})
	})
} 
function_drag('.drag'); 
发布了66 篇原创文章 · 获赞 13 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/weixin_42220533/article/details/103188152