0

如果单击鼠标,如何才能使图像被拖动,而不仅仅是像现在那样跟随鼠标。

<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>
4

1 回答 1

0

需要考虑的关键点是处理图像的 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>
于 2013-11-14T06:30:15.683 回答