原生JS鼠标拖动元素

一、关于拖拽过程分析

  • 1.鼠标按下时,开始拖拽 onmousedown
  • 2.鼠标移动时,div元素跟着移动 onmousemove
  • 3.鼠标释放时,div元素位置固定 onmouseup

二、具体实现

效果图:
在这里插入图片描述
本质上就是拖动div元素,只不过加上了CSS样式

body代码

<body>
<div class="d-box" id="d_box">
    <div class="hd" id="drop">注册信息   (可以拖拽)
            <span id="box_close">【关闭】</span>
    </div>
    <div class="bd"></div>
</div>
</body>

CSS代码

<style>
	.d-box{
		width:400px;
		height:300px;
		border:5px solid #eee;
		box-shadow:2px 2px 2px 2px #666;
		position: absolute;
		top:50%;
		left:50%;
		margin-top: -155px;
		margin-left:-205px;

	}
	.hd{
		width:100%;
		height:25px;
		background-color: #7c9299;
		border-bottom:1px solid #369;
		line-height: 25px; 
		color:white;
		cursor: move;
	}
	#box_close{
		float: right;
		cursor: pointer;
	}
</style>

JS代码

<script type="text/javascript">
    window.onload=function(){
		var box = document.getElementById("d_box");
    	var drop = document.getElementById("drop");
    	//拖拽函数
    	startDrop(drop,box);
	}
	
	function startDrop(current,move) {
	
		//鼠标按下时,开始拖拽  onmousedown
        current.onmousedown = function(event) {
            var event = event || window.event;
	
			//解决鼠标拖之前在哪,拖之后还在哪
            var x = event.clientX - move.offsetLeft - 205;   
            var y = event.clientY - move.offsetTop - 155;  
            
            //鼠标移动时,div元素跟着移动  onmousemove
			document.onmousemove = function(event) {
                var event = event || window.event;
                move.style.left = event.clientX - x + "px";
                move.style.top = event.clientY - y + "px";
            }

        }
        //鼠标释放时,div元素位置固定  onmouseup
        document.onmouseup = function() {  // 鼠标弹起之后, 鼠标继续移动不应该操作
            document.onmousemove = null;
            document.onmouseup=null;
        }
    }
	
</script>

三、新学的知识点

		top:50%;
		left:50%;
		margin-top: -155px;
		margin-left:-205px;

margin-top及left:出现负值?

CSS样式加载到浏览器也是从上到下,top left:50%出现的效果在浏览器偏下,偏右
于是使用margin负值往下拉,视觉效果在正中间

发布了202 篇原创文章 · 获赞 96 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/shang_0122/article/details/104921936