仿百度登录鼠标拖拽事件
百度的登录窗口可以在可视的窗口内进行拖拽,当遇到边界时,进行边界的碰撞检测,当小于边界值时或者大于边界值时,会进行响应的判断。中间还用到了两个封装的函数,用于取窗口可视区宽度和高度。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>拖拽</title>
<style>
#container{
position: absolute;
left: 0;
top: 0;
}
.title{
width: 400px;
height: 30px;
line-height: 30px;
border:1px solid #ccc;
border-bottom:none;
cursor: pointer;
}
.content{
width: 400px;
height: 300px;
text-align: center;
border:1px solid #ccc;
}
</style>
<script>
window.onload = function(){a
var container = document.getElementById("container");
var titleBox = document.getElementById("container").children[0];
titleBox.onmousedown = function(e){
e = e || event;
var mouseleft = e.clientX - container.offsetLeft;
var mousetop= e.clientY - container.offsetTop;
document.onmousemove = function(e){
e = e || event;
var x = e.clientX - mouseleft ;
var y = e.clientY - mousetop ;
if(x < 0){
x = 0 ;
}
if(x > getWidth() - container.offsetWidth){
x = getWidth()- container.offsetWidth;
}
if(y > getHeight() - container.offsetHeight){
y = getHeight() - container.offsetHeight;
}
if(y < 0){
y = 0 ;
}
container.style.left = x+ "px";
container.style.top = y+ "px";
}
}
document.onmouseup = function(){
document.onmousemove = null;
}
}
function getWidth(){
if(window.innerWidth){
return window.innerWidth;
}
else{
if(document.compatMode == "CSS1Compat"){
return document.documentElement.clientWidth;
}
else{
return document.body.clientWidth;
}
}
}
function getHeight(){
if(window.innerHeight){
return window.innerHeight;
}
else{
if(document.compatMode == "CSS1Compat"){
return document.documentElement.clientHeight;
}
else{
return document.body.clientHeight;
}
}
}
</script>
</head>
<body>
<div id="container">
<div class="title">
<img src="logo.png">
<img style="float:right;" src="close.png">
</div>
<div class="content">
<img src="login.png">
</div>
</div>
</body>
</html>