js鼠标拖动div

JavaScript014

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>

(function($) {

$.fn.huadong = function( obj, obja, time ) {

this.height($(window).height()).css({'position':'absolute', 'top':'0px', 'left' : '0px'})//首先把最外层的标签对象设置为浮动, 上边为0, 左边也为0

var left = $(obj).width()//取得左边栏的宽度

$(obj).height($(window).height()).width(0).hide()//将左边栏的高度设置为浏览器的高度, 宽度为0, 并隐藏掉!这样是为了页面载入的时候初始化

$(obja).click(function(){ //给触发按钮绑定点击事件,也就是鼠标点击触发按钮后执行的动作

$(obj).show().animate({'width':left + 'px'}, time)//把左边栏的宽度设置为原来的宽度并显示出来, 根据设定的时间慢慢展现

})

$(obj).mouseout(function(){ //绑定左边栏鼠标移开事件

$(this).animate({'width':'0px'}, time, function(){ $(this).hide()})//又把左边栏的宽度设置为0, 并且隐藏

})

}

})(jQuery)

这个的原理就是,当鼠标左键按下去的时候就显示那个半透明的DIV,并且监控鼠标动作,当鼠标移动时,那个半透明的div也跟着鼠标移动,再当你鼠标左键弹起时半透明的DIV就给他隐藏掉,并且将“自动刷新提示”的那个DIV移动到你鼠标左键弹起的那个位置。