图片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;
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元素的默认行为;
在mousemove事件处理程序中加入event.preventDefault();
取消默认行为,不管拖动的是img的容器元素,还是img本身,都不再有阴影效应存在了;