html5: 將需要點擊打開的代碼加在html5代碼的最後
<div id="login-window">
<form method="post" action="">
<label for="username">用戶:</label>
<input type="text" id="username" name="username" /><br />
<label for="password">密碼:</label>
<input type="password" id="password" name="password" /><br />
<input type="submit" id="login-submit" name="login" /><br />
<a class="signup" href="signup.html">註冊新用戶</a>
</form>
</div>
javascript:
login-window.js
var modal=(function(){//建立一個modal對象
var $window=$(window);
var $modal=$('<div class="modal" />');
var $content=$('<div class="modal-content" />');
var $close=$('<a href="#" class="modal-close">X</a>');
$modal.append($close,$content);//向modal元素添加內容和關閉按鈕
$close.on('click',function(e){//設置點擊關閉的行爲,調用modal的close函數
e.preventDefault();
modal.close();
});
return{
center:function(){ //modal的center函數,由open函數調用,功能爲讓打開的窗口顯示在屏幕的中央
var top=Math.max($window.height()-$modal.outerHeight(),0)/2;
var left=Math.max($window.width()-$modal.outerWidth(),0)/2;
$modal.css({
top:top+$window.scrollTop(),
left:left+$window.scrollLeft()
});
},
open:function(settings){ //open函數,設置打開時的操作
$content.empty().append(settings.content);
$modal.css({
width:settings.width||'auto',
height:settings.height||'auto'
}).appendTo('body');
modal.center();
$(window).on('resize',modal.center);
},
close:function(){ //關閉時的動作
$content.empty();//清空content元素中的內容
$modal.detach();//將modal元素從屏幕上移除
$(window).off('resize',modal.center);
}
};
}());
modal-init.js
(function(){
var $content = $('#login-window').detach(); // Remove modal from page
$('#login').on('click', function() { // Click handler to open modal
modal.open({content: $content, width:340, height:200});
});
}());