首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用鼠标事件的javascript

使用鼠标事件的javascript
EN

Stack Overflow用户
提问于 2013-11-14 00:12:06
回答 1查看 87关注 0票数 0

如果鼠标被点击,我如何才能让图片被拖动,而不是像现在这样跟着鼠标。

代码语言:javascript
运行
复制
<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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-11-14 06:30:15

需要考虑的关键点是处理图像的ondragstart事件。如果不能从它返回false,就意味着浏览器吸收了事件并给出了奇怪的行为。请参阅源中的注释。

试试这件衣服的尺寸。(别忘了改变图像路径)

代码语言:javascript
运行
复制
<!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>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19967074

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档