js基礎學習之--仿百度登錄鼠標拖拽事件

仿百度登錄鼠標拖拽事件

       百度的登錄窗口可以在可視的窗口內進行拖拽,當遇到邊界時,進行邊界的碰撞檢測,當小於邊界值時或者大於邊界值時,會進行響應的判斷。中間還用到了兩個封裝的函數,用於取窗口可視區寬度和高度。



<!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>



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章