js拖动(点击+移动)

双层函数:点击事件+鼠标移动事件


<html>
<head>
    <meta charset="utf-8">
    <title>title>
    <style type="text/css">
        #bar{
            position: relative;
            float: left;
            height: 100px;
            width: 100px;
            background-color: blue;
        }
    style>
head>
<body>
<div id="bar">div>
<script type="text/javascript">
     bar.onmousedown = function(event){
        var bar=document.getElementById("bar");
        var rex=event.clientX-bar.offsetLeft;
        var rey=event.clientY-bar.offsetTop;
            document.onmousemove = function(e){ 
                xX=e.clientX;
                yY=e.clientY;
                bar.style.left=(xX-rex)+"px";
                bar.style.top=(yY-rey)+"px";
            }
}
document.onmouseup=function(){
    document.onmousemove=null;
  }

script>
body>
html>

你可能感兴趣的:(js拖动(点击+移动))