javascript 实现图片拖动

javascript实现图片拖动效果并不难,主要的思路如下

1:给图片绑定监听鼠标按下对象,设置拖动属性为true

2:鼠标抬起:拖动属性为false

    鼠标移动:改变坐标即可,新坐标=图片原始坐标+鼠标移动后坐标-鼠标移动前坐标

注意事项

要给图片的位置属性设为fixed或者absolute,并且要图片复制初始的left和top属性

代码如下

<!DOCTYPE html>
<html>
<head>
    <meta  content="text/html;charset=utf-8" http-equiv="Content-Type">
    <title>test dragging picture</title>
    <script  type="text/javascript" charset="utf-8">
    function draggingP (e) {
        //确认事件
        var e = e || window.event;
        //确认源事件
        var myElement = e.srcElement || e.target;
        //不要默认事件
        if(e.preventDefault) e.preventDefault();
        else  e.returnvalue = false;
        var mypic = document.getElementById("mypic");
        mypic['dragging']=true;//拖动属性为true
        var lef =parseInt(myElement.style.left);
        var to = parseInt(myElement.style.top);
        // alert(lef+"+"+to);
        myElement.onmouseup = function  () {
            mypic['dragging']=false;//拖动属性为false
        }
        document.onmousemove = function  (eMove) {
            var eMove = eMove || window.event;
            if(mypic['dragging']==true){//新坐标
                myElement.style.left = eMove.clientX -e.clientX  + lef+"px";
                myElement.style.top  = eMove.clientY -e.clientY + to+"px";
                return false;
            }
        }

    }
    window.onload = function  () {
        var mypic = document.getElementById("mypic");
        mypic['dragging']=false;
        if(navigator.userAgent.indexOf('MSIE')>0){//IE
            mypic.attachEvent("onmousedown",draggingP);
        }//绑定监听事件
        else{
            mypic.addEventListener("mousedown",draggingP,false);
        }        
    }
     </script>
</head>
<body>
    <img src="http://www.sysu.edu.cn/favicon.ico" alt="sysu" name="mypic" id="mypic" style="position:absolute">
</body>
</html>

 

posted @ 2014-11-06 16:28  2BiTT  阅读(1868)  评论(0编辑  收藏  举报