javascript中的图像拖动

image dragging in javascript

本文关键字:拖动 图像 javascript      更新时间:2024-02-15

我正在尝试用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">

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