图片img或者含有img元素拖拽时的阴影效应问题

<body>
	<!-- <div id="div1"> -->
		<img src="地鼠洞.jpg" alt="" id="img1">
	<!-- </div> -->
</body>

在如上的HTML代码中,静态情况下拖动图片会出现重影;如果添加JS代码实现拖拽功能。
JS代码如下

window.onload = function() {
			var d1 = new Drag('img1');
			d1.init();
		}
		function Drag(id) {
			this.oDiv = document.getElementById(id);
			this.disX = 0;
			this.disY = 0;
		}
		Drag.prototype.init = function() {
			var that = this;
			this.oDiv.onmousedown = function(ev) {
				var ev = ev || window.event;
				ev.preventDefault();
				that.fnDown(ev);
				document.onmousemove = function(eve) {
					var eve = eve || window.event;
					//eve.preventDefault();
					that.fnMove(eve);
				}
				document.onmouseup = function(e) {
					var e = e || window.event;
					that.fnUp(e);
				}
			}
			
			// document.onmousemove = function() {
			// 	that.fnMove()
			// };
			// document.onmouseup = this.fnUp;
		};
		Drag.prototype.fnDown = function(ev) {
			// var ev = ev || window.event;//兼容IE;
			var that = this;
			disX = ev.clientX - this.oDiv.offsetLeft;
			disY = ev.clientY - this.oDiv.offsetTop;
			// document.onmousemove = function(eve) {//这里的事件监听代码可以放在onmousedown的事件处理函数中吗?
			// 	var eve = eve || window.event;
			// 	that.fnMove(eve);
			// }
		};
		Drag.prototype.fnMove = function(ev) {
			var that = this;
			this.oDiv.style.left = (ev.clientX - disX) + 'px';
			this.oDiv.style.top = (ev.clientY - disY) + 'px';
			// document.onmouseup = function(e) {
			// 	var e = e || window.event;
			// 	that.fnUp(e);
			// }
		}
		Drag.prototype.fnUp = function(ev) {
			this.oDiv.style.left = (ev.clientX - disX) + 'px';
			this.oDiv.style.top = (ev.clientY - disY) + 'px';
			document.onmousemove = null;
			document.onmouseup = null;
		}

这时候不管是有没有div元素作为容器,拖动图片时,刚开始会出现下图的重影
在这里插入图片描述鼠标弹起,即mouseup后,才可以正常拖动不再出现阴影;
但如果容器元素尺寸大于图片尺寸时。拖动容器元素不属于图片元素的部分时,就不会出现阴影效应;
图片如果作为div的背景时,拖动div同样也没有阴影效应;
因此可见,阴影效应应该是浏览器的一种对img元素的默认行为;
在mousedown事件处理程序中加入event.preventDefault();取消默认行为,不管拖动的是img的容器元素,还是img本身,都不再有阴影效应存在了;

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值