【视频】鼠标拖拽跟随效果-Miki米奇aries祝由术
春节刚刚过去不久风云修仙路 ,广州现在可是春光明媚铁血剑豪 ,正所谓春天不学习不丹活佛,夏天徒伤悲钱排风情网 ,周厚恩 这么美好的日子魔幻罗盘 极品小散修,来分享一个网页中常见的鼠标拖拽跟随效果王天伦,大致效果如下图:
以下是视频教程飞鸟娱乐 ,有兴趣的童鞋get起来:
以下是源码:
<萨瑶瑶 !doctype html>
<html>
<head>
<meta charset="utf-8">
<title>鼠标拖拽跟随效果</title>
<style>
*{padding: 0; margin: 0;}
.nav{height: 60px; background:skyblue; line-height: 60px;}
.nav span{ margin:0 20px; cursor: pointer;}
.register{width: 500px; height: 300px; border: 1px solid #ccc; position: absolute; left: 0; top: 0; right: 0; bottom: 0; margin:auto; display: none;}
.register .hd{height: 40px; line-height: 40px; background:skyblue; cursor: move;}
.register span{float: right; cursor: pointer;}
</style>
</head>
<body>
<div class="nav">
<span id="btn">点击注册</span>
</div>
<div class="register" id="register">
<div class="hd" id="hd">
注册信息
<span id="hidden">【关闭】</span>
</div>
用户名:
<input type="text">
</div>
<script>
//取数据
var btn = document.getElementById("btn");
var register = document.getElementById("register");
var hd = document.getElementById("hd");
var hidden = document.getElementById("hidden");
btn.onclick = function(){
register.style.display = "block";
}
hidden.onclick = function(){
register.style.display = "none";
register.style.left = 0;
register.style.top = 0;
register.style.margin = "auto";
}
//鼠标按下可以拖动注册框
//鼠标抬起停止拖拽
//拖动注册框杨年华?
//注册最后的坐标是用光标的最终坐标(e.clientX和e.clientY)减去光标在hd里面按下的坐标
//光标在hd里面按下的坐标(e.clientX-register.offsetLeft)
//鼠标按下
hd.onmousedown = function(e){
var e = e||event;
//光标在hd里面坐标
inx = e.clientX - register.offsetLeft;
iny = e.clientY - register.offsetTop;
console.log(inx);
console.log(iny);
//在网页中移动光标事件
document.onmousemove = function(e){
var e = e||event;
//改变注册框坐标
register.style.left = e.clientX - inx + "px";
register.style.top = e.clientY - iny + "px";
register.style.margin = 0;
}
//鼠标抬起蒲提,清空鼠标移动
document.onmouseup = function(){
document.onmousemove = null;
document.onmouseup = null;
}
//阻止默认事件欧阳俊文 ,例如选中文字等
return false;
}
</script>
</body>
</html>