js鼠标拖动div

JavaScript09

js鼠标拖动div,第1张

你的obj.style.left是获取不到的因为该div没有设置style属性所以只要将样式改为行内就行了

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>文哥讨厌IE</title>

</head>

<body>

    <div id="over" onmousedown="down(this,event)" style="width:100pxheight:30pxbackground:redposition:absoluteleft:20pxtop:500px" onmousemove="move(this,event)" onmouseup="seup(this,event)">

        

    </div>

<script type="text/javascript">

    var posX,posY

    var downX,downY

    var mark=false

    function down(obj,event)

    {

        obj.style.cursor="move"

        posX=obj.style.left

        posY=obj.style.top

        downX=event.clientX

        downY=event.clientY

        mark=true

        ///alert(posX)

        ///alert(posY)

    }

    function move(obj,event)

    {

        var moveX=event.clientX

        var moveY=event.clientY

        if (mark) {

            obj.style.left=parseInt(moveX) + parseInt(posX) - parseInt(downX) + "px"

            obj.style.top=parseInt(moveY) + parseInt(posY) - parseInt(downY)+ "px"

        }

    }

    function seup(obj,event)

    {

        if (mark) {

            var moveX=event.clientX

            var moveY=event.clientY

            obj.style.left=parseInt(moveX) + parseInt(posX) - parseInt(downX)+ "px"

            obj.style.top=parseInt(moveY) + parseInt(posY) - parseInt(downY)+ "px"

            downX=moveX

            downY=moveY

        }

        obj.style.cursor="default"

            mark = false 

    }

</script>

</body>

</html>

var drag_ = false

var D = new Function('obj', 'return document.getElementById(obj)')

var oevent = new Function('e', 'if (!e) e = window.eventreturn e')

function Move_obj(obj) {

var x, y

D(obj).onmousedown = function (e) {

drag_ = true

with (this) {

style.position = "absolute"var temp1 = offsetLeftvar temp2 = offsetTop

x = oevent(e).clientXy = oevent(e).clientY

document.onmousemove = function (e) {

if (!drag_) return false

with (this) {

style.left = temp1 + oevent(e).clientX - x + "px"

style.top = temp2 + oevent(e).clientY - y + "px"

}

}

}

document.onmouseup = new Function("drag_=false")

}

}

<div onmousedown="Move_obj(this.id)" id="dd" style="width:100pxheight:100pxbackground:red"></div>

如果需要以后都留在此位置,需把当前位置的坐标保存到数据库,下次打开时读取数据加载div