鼠标拖拽效果很常见,例如百度的登录页,点击登录会弹出一个窗口,并且这个窗口可以拖动;首先,要涉及到鼠标的三个事件,分别为鼠标按下、移动、松开;onmousedown onmousemove onmouseup
下面是代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JS鼠标拖拽</title>
<style type="text/css">
* {
margin: 0px;
padding: 0px;
}
.mask {
width: 100%;
height: 4000px;
position: relative;
left: 0px;
top: 0px;
position: fixed;
background-color: #000;
opacity: 0.5;
fill-opacity: 50;
display: none;
}
.mov {
position: fixed;
left: 50%;
margin-left: -200px;
width: 400px;
height: 300px;
background-color: #fff;
top: 50%;
margin-top: -150px;
display: none;
}
.title {
cursor: move;
width: 400px;
height: 50px;
background-color: #ccc;
}
</style>
</head>
<body>
<div id="mask" class="mask">
</div>
<div id="mov" class="mov">
<div class="title" id="title" onmousedown="start()" onmouseup="stop()" onmouseout="stop()" onmousemove="zzz()"></div>
</div>
<input type="button" value="登录" onclick="show()" />
</body>
<script type="text/javascript">
var neng = 0;
function show() {
document.getElementById("mask").style.display = "block"
document.getElementById("mov").style.display = "block"
}
function zzz() {
if (neng == 1) {
var a = window.event || kk; //IE谷歌 或 谷歌火狐
var heng = a.clientX
var zong = a.clientY
//clientX有极值 200-1149==屏幕宽-宽度的一半
//clientY极值25-300==屏幕高-高度的一半
var pingk = document.documentElement.clientWidth; //屏宽不包括滚动条
var pingh = document.documentElement.clientHeight;
if(heng<=200){
heng=200;
}else if(heng>=pingk-200){
heng=pingk-200
}else{
}
if(zong<=25){
zong=25;
}else if(zong>=pingh-(300-25)){
zong=pingh-(300-25)
}else{
}
var s = document.getElementById("mov")
s.style.left = heng + "px"
s.style.top = zong +125 + "px"
}
}
function start(){
neng = 1;
}
function stop(){
neng = 0;
}
</script>
</html>