點擊「我要報名」按鈕,半透明遮罩淡入,彈出層從高度 0 動畫展開至完整高度,垂直置中;點擊關閉或遮罩,反向動畫收合並移除。
// 僅需在頁面放置觸發按鈕
<h1 class="bm"><a href="javascript:;">我要報名</a></h1>
.layer_bg {
position: fixed; top: 0; left: 0; width: 100%; height: 100%;
background: rgba(0,0,0,0.7); z-index: 1000; display: none;
}
.layer_item {
position: fixed; left: 50%; top: 50%;
width: 600px; margin-left: -300px; /* 水平置中 */
background: #fff; z-index: 1001; overflow: hidden;
transform: translateY(-50%); /* 垂直置中核心 */
display: none;
}
.layer_title { background: #FF4E00; height: 75px; line-height: 75px; color: #fff; }
.layer_title h1 { float: left; font-size: 35px; text-indent: 20px; font-weight: normal; }
.layer_title a { float: right; width: 75px; height: 75px; font-size: 60px; text-align: center; text-decoration: none; color: #fff; background: #535961; }
.layer_item ul { padding: 10px 0; }
.layer_item li { line-height: 35px; padding: 10px 0; }
.layer_item li span { float: left; width: 100px; text-align: right; padding-right: 10px; text-indent: 20px; }
.layer_item li span b { color: red; }
.layer_txt { float: left; width: 300px; height: 23px; line-height: 23px; padding: 5px; border: 1px solid #dfdfdf; }
#message { width: 400px; height: 150px; }
.layer_btn { padding-bottom: 40px; text-align: center; }
.layer_submit_btn { width: 100px; height: 40px; background: #FF4E00; color: #fff; border: none; font: 14px 'Microsoft YaHei'; cursor: pointer; border-radius: 4px; }
$(function() {
// 1. 動態建立彈出層 DOM
var $bg = $('');
var $layer = $(`
`);
$('body').append($bg).append($layer);
// 2. 開啟動畫
$('.bm a').on('click', function() {
$bg.fadeIn(200);
$layer.show().css({ height: 0, marginTop: 0 }).animate({ height: $layer[0].scrollHeight }, 400);
});
// 3. 關閉動畫(綁定關閉鈕 + 遮罩點擊)
function closeLayer() {
$layer.animate({ height: 0 }, 200, function() {
$bg.fadeOut(200);
$layer.hide();
});
}
$('.layer_title a, .layer_bg').on('click', closeLayer);
// 4. 表單提交驗證(示範)
$('.layer_submit_btn').on('click', function() {
var valid = true;
$layer.find('[required]').each(function() {
if (!$.trim(this.value)) {
$(this).css('border-color', 'red');
valid = false;
} else {
$(this).css('border-color', '#dfdfdf');
}
});
if (!valid) return alert('請填寫必填欄位');
// AJAX 提交...
console.log('提交資料:', $layer.find('input, textarea').serialize());
closeLayer();
});
// 5. ESC 鍵關閉
$(document).on('keydown', function(e) {
if (e.key === 'Escape' && $layer.is(':visible')) closeLayer();
});
});
transform: scaleY(0) -> scaleY(1) + transform-origin: top center 避免佈局抖動。role="dialog"、aria-modal="true"、焦點陷阱。90vw,max-width: 600px。$layer.is(':animated')。