Bulma Modal 模態窗 的 JavaScript 程式碼
本文是給那些不想自己寫 JavaScript 程式碼,而只想用跟 Bulma 官方網站 modal 模態窗 [1] 一樣程式碼的人。
此 JavaScript 程式碼來自官方網站所用的 main.js [2] 。 我把程式碼放在本文以方便透過谷歌或其他搜尋引擎來搜索。
'use strict';
document.addEventListener('DOMContentLoaded', function () {
// Modals
var rootEl = document.documentElement;
var $modals = getAll('.modal');
var $modalButtons = getAll('.modal-button');
var $modalCloses = getAll('.modal-background, .modal-close, .modal-card-head .delete, .modal-card-foot .button');
if ($modalButtons.length > 0) {
$modalButtons.forEach(function ($el) {
$el.addEventListener('click', function () {
var target = $el.dataset.target;
var $target = document.getElementById(target);
rootEl.classList.add('is-clipped');
$target.classList.add('is-active');
});
});
}
if ($modalCloses.length > 0) {
$modalCloses.forEach(function ($el) {
$el.addEventListener('click', function () {
closeModals();
});
});
}
document.addEventListener('keydown', function (event) {
var e = event || window.event;
if (e.keyCode === 27) {
closeModals();
}
});
function closeModals() {
rootEl.classList.remove('is-clipped');
$modals.forEach(function ($el) {
$el.classList.remove('is-active');
});
}
// Functions
function getAll(selector) {
return Array.prototype.slice.call(document.querySelectorAll(selector), 0);
}
});
Demo:
Launch image modal
You might be interested in ...
Tested on:
- Chromium 64.0.3282.140 on Ubuntu 17.10 (64-bit)
- Bulma 0.6.2
References:
[1] | Modal | Bulma: a modern CSS framework based on Flexbox |
[2] | https://bulma.io/lib/main.js?v=201802091742 |