图像在javascript中拖动

时间:2015-02-20 10:12:37

标签: javascript jquery

我想在javascript中拖动图片 我知道这很容易使用jQuery,但我想使用javascript 这是代码,但它无法正常工作

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>dragImage</title>
        <meta name="author" content="engy" />
        <!-- Date: 2015-02-17 -->
    </head>
    <body>
        <!--<img src="bbe.jpg" style="width:104px;height:128px">-->
        <!-- <img id = "img" src="bbe.jpg" style="position:absolute; TOP:posY; LEFT:posX; WIDTH:50px; HEIGHT:50px"> -->
        <!--top=y=155px;left=x=70px;-->



    <script>
        var flagdown = 0;
    </script>
    <script>
        function up() {

            flagdown = 0;
        }

        function down() {
            //document.write("jk");
            flagdown = 1;
        }

        function move(e) {
            if (flagdown == 1) {
                var posX = e.clientX;
                var posY = e.clientY;
                document.getElementById("img").style.marginLeft = posX;
                document.getElementById("img").style.marginTop = posY;
            }

        }
        document.onmousemove = move;    
    </script>
    </body>
</html>
谁能帮助我吗? 我已经在很多浏览器中尝试过但它仍然无法正常工作

var flagdown = 0;

function up() {

  flagdown = 0;
}

function down() {
  //document.write("jk");
  flagdown = 1;
}

function move(e) {
  if (flagdown == 1) {
    var posX = e.clientX;
    var posY = e.clientY;
    document.getElementById("img").style.marginLeft = posX;
    document.getElementById("img").style.marginTop = posY;
  }

}
document.onmousemove = move;
<img onmouseup="up()" onmousedown="down()" id="img" src="bbe.jpg" draggable="true" width="50" height="50">

1 个答案:

答案 0 :(得分:0)

<!DOCTYPE HTML>
<html>
<head>
<style>
#div1 {width:350px;height:70px;padding:10px;border:1px solid #aaaaaa;}
</style>
<script>
function allowDrop(ev) {
    ev.preventDefault();
}

function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>

<p>Drag image into the rectangle:</p>

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br>
<img id="drag1" src="img_logo.gif" draggable="true" ondragstart="drag(event)" width="336" height="100">

</body>
</html>
相关问题