轻松创建可点击元素与其在模态框中扩展版本之间的无缝过渡。
你甚至可以通过结合使用 布局 ID 并指定 子元素,从指定根之外的元素进行动画。
模态对话框动画代码示例
import { createLayout, utils } from 'animejs';
const buttons = utils.$('button');
// Create demo dialog and append it to the body
const $dialog = document.createElement('dialog');
$dialog.id = 'layout-dialog';
document.body.appendChild($dialog);
// Create the modal layout by setting the dialog as the root
// Since the elements are not yet part of the modal root, it's necessary to specify all animated children
// to tell the layout what to look for during an update
const modalLayout = createLayout($dialog, {
children: ['.item', 'h2', 'h3', 'p'],
properties: ['--overlay-alpha'],
});
const closeModal = (e) => {
let $item;
modalLayout.update(({ root }) => {
$dialog.close();
$item = buttons.find(item => item.classList.contains('is-open'));
$item.classList.remove('is-open'); // Makes the clicked element visible again
$item.focus(); // Focus to the closed element to preserve the keyboard navigation flow
});
};
const openModal = e => {
const $target = e.target;
const $item = $target.closest('.item');
const $clone = $item.cloneNode(true);
$dialog.innerHTML = ''; // Make sure old clones are removed from the modal before adding a new one
$dialog.appendChild($clone); // Append the clicked element clone to the modal
modalLayout.update(() => {
$dialog.showModal(); // Open the modal
$item.classList.add('is-open'); // Hide the clicked element
}, {
duration: $item.dataset.duration // Custom duration depending of the button clicked
});
}
buttons.forEach($button => $button.addEventListener('click', openModal));
$dialog.addEventListener('cancel', closeModal);
$dialog.addEventListener('click', closeModal);
<div class="large layout centered row">
<div class="layout-container col grid-layout row">
<button data-layout-id="A" data-duration="500" class="button item col">
<h2 data-layout-id="A-title">Item A</h2>
<h3 data-layout-id="A-duration">(500ms)</h3>
<p>This p tag is hidden by default and only visible when appended inside the dialog element. Its position and opacity are automatically animated.</p>
</button>
<button data-layout-id="B" data-duration="1000" class="button item col">
<h2 data-layout-id="B-title">Item B</h2>
<h3 data-layout-id="B-duration">(1000ms)</h3>
<p>This p tag is hidden by default and only visible when appended inside the dialog element. Its position and opacity are automatically animated.</p>
</button>
<button data-layout-id="C" data-duration="2000" class="button item col">
<h2 data-layout-id="C-title">Item C</h2>
<h3 data-layout-id="B-duration">(2000ms)</h3>
<p>This p tag is hidden by default and only visible when appended inside the dialog element. Its position and opacity are automatically animated.</p>
</button>
</div>
</div>