面向对象-拖拽

本文介绍了一个简单的拖拽实现方案,通过监听鼠标事件并调整元素位置来实现拖拽效果。为防止浏览器默认行为干扰,文中使用return false阻止默认操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

拖拽的时候,如果触发了浏览器默认行为,就会影响效果,所以需要的时候要阻止浏览器默认行为。

  解决: 标准:阻止默认行为 ,return false 即可。

                非标准ie:全局捕获。obj.setCapture();

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			div{width: 100px;height: 100px;background: red;position: absolute;cursor: pointer;}
			#div2{background: yellow;left: 300px;}
		</style>
		<script type="text/javascript">

			window.onload =function(){
				new Drag('div1');
				new Drag('div2');
			} ;
			
			
			function Drag(id){
				var _this = this;
				this.cliX = 0;
				this.cliY = 0;
				this.oDiv = document.getElementById(id);
				this.oDiv.onmousedown = function(){
					_this.fnDowm();
				};
			}
			
			Drag.prototype.fnDowm =  function(ev) {
			
				var ev = ev || event;
				var _this = this;
				this.cliX = ev.clientX - this.oDiv.offsetLeft;
				this.cliY = ev.clientY - this.oDiv.offsetTop;
			
				document.onmousemove =function(){
					_this.fnMove();
					
				return false;
				};
				
				document.onmouseup = function(){
					_this.fnUp();
				};
			}

			Drag.prototype.fnMove = function (ev) {
				var ev = ev || event;
				this.oDiv.style.left = ev.clientX - this.cliX +'px';
				this.oDiv.style.top = ev.clientY -this.cliY+ 'px';
			}
			
			Drag.prototype.fnUp = function (){
					document.onmouseup = null;
					document.onmousemove = null;
			}
		</script>
	</head>
	<body>
		<div id="div1"></div>
		<div id="div2"></div>
	</body>
</html>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值