close
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
	<style type="text/css">
		*{
			margin: 0;
			padding: 0;
			list-style:none;
		}
		body{
			height: 100vh;
			position: relative;
			padding: 20px;
			box-sizing: border-box;
		}
		.newBox{
			position: fixed;
			border: 1px solid #aaa;
			text-align: center;
			padding: 10px;
			box-sizing: border-box;
		}
	</style>
</head>
<body>
	<button id="btn">按我</button>
	<div id="lightbox">
		<img src="https://api.fnkr.net/testimg/100x100/a00/FFF/?text=LightBox">
		<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Blanditiis, pariatur! Alias aspernatur, animi adipisci amet similique ipsam, incidunt laborum totam!</p>
	</div>
	<script type="text/javascript"> //定義
		var myFunction=(function(){
			//加錢字號避免撞名
			var $window = $(window);
			var $newBox=$('<div class="newBox"></div>');
			var $newContent=$('<div class="newBoxContent"></div>');
			var $newClose=$('<button class="newBoxClose">關掉</button>');
			$newBox.append($newContent,$newClose);//一次加兩個孩子

			$newClose.on('click',function(){
				myFunction.close();
			});

			return{
				center:function(){
							//從兩數中選比較高者(避免負數)	//含外距
					var dtop = Math.max($window.height()-$newBox.outerHeight(),0)/2;
					var dleft = Math.max($window.width()-$newBox.outerWidth(),0)/2;
					$newBox.css({
						top:dtop+$window.scrollTop(),
						left:dleft+$window.scrollLeft()
					});
				},
				open:function(data){
							//刪掉所有兒子 //加上執行時輸入的物件的content屬性
					$newContent.empty().append(data.content);
					$newBox.css({
						width:data.width || 'auto', //執行時沒輸入就代入auto
						height:data.height || 'auto'
					}).appendTo('body'); //當body的最後一個新兒子

					myFunction.center(); //若resize事件發生,就執行剛剛定義好的center方法
					$window.on('resize',myFunction.center);
				},
				close:function(){
					$newContent.empty();
					$newBox.detach();
					$window.off('resize',myFunction.center);//監聽器關掉
				}
			}
		}());
	</script>
	<script type="text/javascript"> //執行
		(function(){
			var $newContent=$('#lightbox').detach();
			$('#btn').on('click',function(){
				myFunction.open({
					content:$newContent,
					width:340,
					height:300
				})
			});
		}());
	</script>
</body>
</html>
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 Jerry 的頭像
    Jerry

    Bug倉庫 // 程式日記

    Jerry 發表在 痞客邦 留言(0) 人氣()