JavaScript拖拽图片一

               

本文演示如何将一张图片用鼠标拖拽到某个位置。

先看html代码:

<html>  <head>    <title>drag demo</title>    <script src="js/drag.js" type="text/javascript"></script>  </head>  <body onload="init()">    <div id="icon1"   onmousedown="mouseDown(event)"  style="left:1px; top: 1px; position: absolute;">      <img alt="" border="0" src="/img/2.jpg"></img>    </div>  </body></html>


注意,必须在style中指定三个属性:

left,top属性值可以为任意有效数值,position必须是absolute

为了便于扩展,将图片包装在div中,下面的JavaScript代码其实是拖动div。


然后看看drag.js文件:

function init() window.document.onmousemove = mouseMove; window.document.onmouseup = mouseUp; window.document.ondragstart = mouseStop;}function mouseDown(e) window.dragObj = e.currentTarget; if (window.dragObj !== null) {  window.clickLeft = window.event.x - parseInt(dragObj.style.left);  window.clickTop = window.event.y - parseInt(dragObj.style.top);  window.dragObj.style.zIndex += 1; }}function mouseStop() window.event.returnValue = false;}function mouseMove() if (window.dragObj !== null ) {  window.dragObj.style.left = window.event.x - window.clickLeft;  window.dragObj.style.top = window.event.y - window.clickTop; }}function mouseUp() window.dragObj = null;}

ondragStart事件被禁用。

主要就是mouseDown,mouseMove和mouseUp三个函数。

注意window.clickLeft和window.clickTop,它们是在点击图片的时候计算的,代表鼠标在图片里的位置(距离图片左上角的x和y值)。

它们用来保证在移动后鼠标仍然停留在图片的相对位置,通过将鼠标的位置减去这两个偏移值。



           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

猜你喜欢

转载自blog.csdn.net/fduffyyg/article/details/87599965