js实现弹窗拖拽功能

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			* {
				margin: 0;
				padding: 0;
			}
			a {
				text-decoration: none;
			}
			html,
			body {
				width: 100%;
				height: 100%;
			}
			.box {
				width: 100%;
				top: 0;
				left: 0;
				bottom: 0;
				right: 0;
				height: 100%;
				background: rgba(0, 0, 0, 0.4);
				position: fixed;
				display: none;
			}

			.box1 {
				width: 60%;
				height: 60%;
				margin: 50 auto;
				background: #fff;
				position: absolute;
				left: 300px;
				top: 100px;
				border-radius: 2px;
				box-shadow: 0 1px 3px rgb(0 0 0 / 30%);
			}
			.list {
				height: 50px;
				background-color: #4491e1;
				font-size: 18px;
				line-height: 50px;
				position: relative;
				padding: 0 20px;
				display: flex;
				justify-content: space-between;
				color: #fff;
			}
			#ipt {
				color: #fff;
			}
		</style>
	</head>
	<body>
		<input type="button" value="点击弹出窗口" id="btn" />
		<div class="box">
			<div class="box1">
				<div class="list">
					<div>标题</div>
					<a href="javascript:;" id="ipt">x</a>
				</div>
				<div>放内容</div>
			</div>
		</div>
		<script type="text/javascript">
			//点击按钮弹出窗口
			let btn = document.querySelector('#btn')
			let box = document.querySelector('.box')
			btn.onclick = function() {
				// btn.style.display = 'none'	
				box.style.display = 'block'
			}
			//点击按钮关闭窗口
			let ipt = document.querySelector('#ipt')
			ipt.onclick = function() {
				box.style.display = 'none'
				btn.style.display = 'block'
			}
			//拖拽
			let list = document.querySelector('.list')
			let box1 = document.querySelector('.box1')
			list.onmousedown = function(e) {
				console.log(e);
				console.log(box1.offsetLeft);
				console.log(box1.offsetTop);
				let offsetX = e.pageX - box1.offsetLeft
				let offsetY = e.pageY - box1.offsetTop

				document.onmousemove = function(d) {
					let left = d.pageX - offsetX;
					let top = d.pageY - offsetY;

					box1.style.left = left + 'px'
					box1.style.top = top + 'px'
				}
				//鼠标抬起,清除鼠标移动事件			
				document.onmouseup = function() {
					document.onmousemove = null;
				}
			}
		</script>
	</body>
</html>

上一篇:Day04


下一篇:Java内部类的理解与使用