如果鼠标被点击,我如何才能让图片被拖动,而不是像现在这样跟着鼠标。
<head>
<style>
#flying {
position: absolute;
}
</style>
<script type="text/javascript">
function UpdateFlyingObj (event) {
var mouseX = Math.round (event.clientX);
var mouseY = Math.round (event.clientY);
var flyingObj = document.getElementById ("flying");
flyingObj.style.left = mouseX + "px";
flyingObj.style.top = mouseY + "px";
}
this.onmouseup = function() {
document.onmousemove = null
}
</script>
</head>
<body onmousemove="UpdateFlyingObj (event);" >
<h1><center>Homework 13.7<center></h1>
<div style="height:1000px;"></div>
<img id="flying" src="flying.gif" />
</body>发布于 2013-11-14 06:30:15
需要考虑的关键点是处理图像的ondragstart事件。如果不能从它返回false,就意味着浏览器吸收了事件并给出了奇怪的行为。请参阅源中的注释。
试试这件衣服的尺寸。(别忘了改变图像路径)
<!DOCTYPE html>
<html>
<head>
<style>
#flying
{
position: absolute;
}
</style>
<script>
function byId(e){return document.getElementById(e);}
window.addEventListener('load', myInitFunc, false);
function myInitFunc()
{
byId('flying').addEventListener('mousedown', onImgMouseDown, false);
}
function onImgMouseDown(e)
{
e = e || event;
var mElem = this;
var initMx = e.pageX;
var initMy = e.pageY;
var initElemX = this.offsetLeft;
var initElemY = this.offsetTop;
var dx = initMx - initElemX;
var dy = initMy - initElemY;
document.onmousemove = function(e)
{
e = e || event;
mElem.style.left = e.pageX-dx+'px';
mElem.style.top = e.pageY-dy+'px';
}
this.onmouseup = function()
{
document.onmousemove = null;
}
// try to comment-out the below line
// doing so means the browser absorbs the ondragstart event and (in Chrome) drags a reduced-opacity copy of
// the image, overlaid with a circle that has a diagonal line through it. - just like the usuall behaviour for
// dragging an image on a webpage.
this.ondragstart = function() { return false; }
}
</script>
</head>
<body>
<h1><center>Homework 13.7<center></h1>
<img id="flying" src="img/opera.svg"/>
</body>
</html>https://stackoverflow.com/questions/19967074
复制相似问题