当前位置:首页 » JavaScript » JavaScript拖拽图片
JavaScript拖拽图片
来自:新思网络时间:2012-07-11 08:50:50

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

先看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事件被禁用。
关键词:JavaScript