1. 程式人生 > >cookie結合js 實現記住的拖拽

cookie結合js 實現記住的拖拽

div 位置 highlight cti top mov type logs 加載

哈嘍!!!我胡漢三又回來啦!!!有木有記掛挪啊!咱們今天說一個

cookie結合JS的小案例哦!

話不多說直接上代碼:

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<style>
			#drag {
				width: 200px;
				height: 200px;
				text-align: center;
				line-height: 200px;
				background: greenyellow;
				position: absolute;
				top: 0;
				left: 0;
				cursor: pointer;
			}
		</style>
	</head>

	<body>
		<div id="drag">我竟然Σ(っ°Д°;)っ被拖走了!</div>
	</body>
	<script>
		function addCookie(name, value, iDay) {
			var oDate = new Date();
			oDate.setDate(oDate.getDate() + iDay);
			document.cookie = name + ‘=‘ + value + ‘; path=/; expires=‘ + oDate;
		}

		//頁面加載的時候調用getCookie方法
		//獲取cookie
		function getCookie(name) {
			var arr = document.cookie.split(‘; ‘);
			for(var i = 0; i < arr.length; i++) {
				var arr2 = arr[i].split(‘=‘);

				return(arr2[0] == name) && arr2[1]
			}
			return ‘‘;
		}

		window.onload = function() {
			var oDiv = document.getElementById(‘drag‘);
			drag(oDiv);
			var move_by = getCookie(‘move_cood‘);
			if(move_by) {
				var str = eval(‘(‘ + move_by + ‘)‘);
				//移動時重新得到物體的距離
				oDiv.style.left = str[0] + ‘px‘;
				oDiv.style.top = str[1] + ‘px‘;
			}

			function drag(obj) {
				//鼠標落下
				obj.onmousedown = function(ev) {
					var oEvent = ev || event; //解決兼容

					var disX = oEvent.clientX - obj.offsetLeft,
						disY = oEvent.clientY - obj.offsetTop;
					//鼠標移動
					document.onmousemove = function(ev) {
						var oEvent = ev || event;
						//獲取鼠標點擊屏幕時的那個點,然後減去被拖拽物體距離左邊的一個距離
						obj.style.left = oEvent.clientX - disX + ‘px‘;
						obj.style.top = oEvent.clientY - disY + ‘px‘;
					};
					//鼠標擡起
					document.onmouseup = function() {
						document.onmousemove = null; //當鼠標彈起時不再移動
						document.onmouseup = null; //預防鼠標放上去的時候還會移動
						//releaseCapture 鼠標的捕獲和釋放
						obj.releaseCapture && obj.releaseCapture();

						//通過addCookie方法,把物體拖動停止的位置存在了cookie裏面
						addCookie(‘move_cood‘, ‘[‘ + obj.offsetLeft + ‘,‘ + obj.offsetTop + ‘]‘, 10);
					};
					//捕獲鼠標
					obj.setCapture && obj.setCapture();
					//阻止選中文字
					return false;
				};
			}
		};
	</script>

</html>

  就是這樣滴!!!你學會了嗎???

cookie結合js 實現記住的拖拽