html+js实现一个拖动的DIV

html+js实现一个拖动的DIV,第1张

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

<html>

<head>

<meta http-equiv="Content-Type" content="text/html charset=UTF-8">

<title>拖动DIV</title>

<style type="text/css"> 

div{

width:200px

height:200px

background-color:#cef

position:absolute

}

</style>

<script type="text/javascript"> 

function movestart(obj) {

var width=event.offsetX

var height=event.offsetY

document.onmousemove=function() {

obj.style.left=event.clientX-width+"px"

obj.style.top=event.clientY-height+"px"

}

}

function moveend() {

document.onmousemove=null

}

</script>

</head>

<body>

<div id="mydv" onmousedown="movestart(this)" onmouseup="moveend()">这个可以拖动</div>

</body>

</html>

你的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>


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/7308224.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-04
下一篇 2023-04-04

发表评论

登录后才能评论

评论列表(0条)

保存