点击拖拽事件

$('.box').mousedown(function(e) {
						var e = e || window.event;
						var x = e.pageX; //box里面点击x位置
						var y = e.pageY; //box里面点击y轴位置
						var widt = $(window).width(); //浏览器宽
						var heigh = $(window).height(); //高
						var boxW = $('.box').width(); //盒子宽
						var boxH = $('.box').height(); //高
						var posX = $('.box').position().left; //距离左边
						var posY = $('.box').position().top; //距离上面
						$(document).mousemove(function(e) { //鼠标按下未松开
							var e = e || window.event;
							var newx = e.pageX; //  鼠标按下x轴
							var newy = e.pageY; //  鼠标按下y轴
							var movx = newx - x; //浏览器dom 鼠标移动的x - 原来在盒子里面鼠标按下的位置
							var movy = newy - y; //同理
							var newmovx = posX + movx; //  偏移的x轴位置 + 上面浏览器dom 鼠标移动的x - 原来在盒子里面鼠标按下的位置
							var newmovy = posY + movy; //同理
							if(posX + movx >= widt - boxW) //如果 距离左边值+浏览器dom 鼠标移动的x - 原来在盒子里面鼠标按下的位置
							{ //大于  浏览器宽-盒子宽
								newmovx = widt - boxW; // 需要移动的 位置 =  浏览器宽-盒子宽
							}
							if(posX + movx <= 0) //如果 偏移x轴位置 +  浏览器dom 鼠标移动的x - 原来在盒子里面鼠标按下的位置
							{
								newmovx = 0; //就代表 鼠标移出去了, 给0
							}
							if(posY + movy >= heigh - boxH) {
								newmovy = heigh - boxH;
							}
							if(posY + movy <= 0) {
								newmovy = 0;
							}
							$('.box').css({
								'left': newmovx + 'px',
								'top': newmovy + 'px'
							}) //set
						})
					})
					$('.box').mouseup(function(e) {
						var e = e || window.event;
						upLeft = e.pageX;
						upTop = e.pageY;
						console.log(upLeft, upTop)
						$(document).off('mousemove');
					}) //当点击在盒子上的鼠标松开的 时候 清除事件
					//页面禁止双击选中

html

<div id="geographicals">
	<div class="box">
		<span><i class="glyphicon glyphicon-map-marker"></i></span> <br />
		<span id="measurement"></span>
	</div>
</div>

在这里插入图片描述

#geographicals {
	width: 100%;
	height: 300px;
	border: 1px solid #B2B2B2;
	background-color: #93D1FF;
}

#geographicals>img {
	width: 100%;
	height: 100%;
	position: relative;
}

.box {
	text-align: center;
	display: inline-block;
	position: absolute;
	width: 72px;
	height: 40px;
}

.box>span {
	color: red;
}

.box>span>i {
	font-size: 20px;
}
发布了17 篇原创文章 · 获赞 11 · 访问量 570

猜你喜欢

转载自blog.csdn.net/weixin_45563734/article/details/101694260