JS之拖拽案例

需求:在指定位置按住鼠标左键移动对话框
分析:鼠标按下(获取鼠标在盒子中的位置)。触动事件(获取鼠标的位置),移动在更换对话框的位置(盒子在页面中的位置=鼠标的位置-鼠标在盒子中 的距离)
鼠标按下onmousedown 鼠标弹起:onmouseup 鼠标移动:onmousemove
步骤:
1.老三步和新五步
2.把鼠标的坐标赋值给对话框,禁止文本选中

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
    <title></title>
<style type="text/css">
*{
    margin: 0;
    padding: 0;
}
.nav{
    height: 30px;
    background: #036663;
    border-bottom: 1px solid #369;
    line-height: 30px;
    padding-left: 30px;
}
.nav a{
    color: #fff;
    text-align: center;
    font-size: 14px;
    text-decoration: none;
}
.d-box{
    width:400px;
    height: 300px;
    border:2px solid #036663;
    box-shadow: 2px 2px 2px 2px #666;
    position: absolute;
    top: 40%;
    left: 40%;
}
.hd{
    width: 100%;
    height: 25px;
    background-color: #036663;
    border-bottom: 1px solid #369;
    line-height: 25px;
    color: white;
    cursor: move;
}
#box_close{
    float: right;
    cursor:pointer;
}
</style>
</head>
<body>
<!-- 顶部注册部分,无用 -->
<div class="nav">
<a href="#" id="register">注册信息</a>
</div>
<!-- 我们移动的对话框 -->
<div class="d-box" id="d_box">
    <div class="hd" id="drop">
        <i>注册信息(可拖拽)</i>
        <span id="box_close">【关闭】</span>
    </div>
    <div class="bd"></div>
</div>
<script type="text/javascript">
window.onload = function(){
//需求:在指定位置按住鼠标左键移动对话框
    //分析:鼠标按下。触动事件,移动在更换对话框的位置
    //鼠标按下onmousedown 鼠标弹起:onmouseup  鼠标移动:onmousemove
    //步骤:
    //1.老三步和新五步
    //2.把鼠标的坐标赋值给对话框
    
    
    //1.老三步和新五步
var box = document.getElementById("d_box");
var drop = document.getElementById("drop");

//鼠标按下,再移动对话框
drop.onmousedown = function(event){

//先获取鼠标在盒子中的位置,在将来移动的时候减去,以保证鼠标在盒子中的位置
event = event || window.event;//兼容获取的事件对象
var pagex = event.pageX || scroll().left + event.clientX;//鼠标的位置
var pagey = event.pageY || scroll().top + event.clientY;
var mousedivx = pagex - box.offsetLeft;//鼠标在盒子中的位置
var mousedivy = pagey - box.offsetTop;
   document.onmousemove = function(event){
event = event || window.event;
//鼠标的位置
var mousex = event.pageX || scroll().left + event.clientX;
var mousey = event.pageY || scroll().top + event.clientY;
//二次处理鼠标的位置
mousex = mousex -mousedivx;
mousey = mousey - mousedivy;
//给box赋值
box.style.left = mousex +"px";
box.style.top = mousey +"px";
//禁止选中文本框
window.getSelection?window.getSelection().removeAllRanges():document.selection().empty();
     } 
}
//鼠标松开,解绑事件
drop.onmouseup = function(){
    document.onmousemove = null;
}
}
</script>
</body>
</html>

 

posted @ 2018-01-03 14:26  乖乖乖码  阅读(432)  评论(0编辑  收藏  举报