<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body{
padding: 400px 200px 1px;
}
* {
padding: 0;
margin: 0;
}
button {
position: relative; /* 下文中会用到的相对绝对位置 */
overflow: hidden;
transition: background 400ms ease-in-out; /* 设置切换 */
color: #fff;
background-color: #662d91;
padding: 1rem 2rem;
font-family: 'Roboto', sans-serif;
outline: 0;
border: 0;
border-radius: 0.25rem;
box-shadow: 0 0 0.5rem rgba(0, 0, 0, 0.2);
cursor: pointer;
}
span.ripple {
position: absolute; /* 上文中我们提到过的相对绝对位置 */
border-radius: 50%;
transform: scale(0);
animation: ripple 600ms linear;
background-color: rgba(255, 255, 255, 0.2);
}
@keyframes ripple {
to {
transform: scale(4);
opacity: 0;
}
}
</style>
</head>
<body>
<button class="ripple">一个简简单单的按钮</button>
</body>
</html>
<script>
const showRipple = (event) => {
const btn = event.currentTarget;
const circle = document.createElement('span');
const diameter = Math.max(btn.clientWidth, btn.clientHeight);
const radius = diameter / 2;
circle.style.width = circle.style.height = `${diameter}px`;
circle.style.left = `${event.clientX - (btn.offsetLeft + radius)}px`;
circle.style.top = `${event.clientY - (btn.offsetTop + radius)}px`;
circle.classList.add('ripple');
btn.appendChild(circle);
setTimeout(() => {
btn.removeChild(circle);
}, 1000); /* 记得移除元素 */
};
[...document.querySelectorAll('.ripple')].forEach((btn) => {
btn.addEventListener('click', showRipple);
});
const listener = (mutationRecord) => {
/**
* @param mutationRecord: Callback of MutationObserve
* => mutations: MutationRecord[]
*/
for (let mutation of mutationRecord) {
if (mutation.type === 'attributes' && mutation.attributeName === 'ripple' && !mutation.target.hasAttribute('ripple-init')) {
mutation.target.addEventListener('click', showRipple);
mutation.target.setAttribute('ripple-init', '');
}
if (mutation.addedNodes && mutation.addedNodes.length > 0) {
mutation.addedNodes.forEach((node) => {
if (node.nodeType === Node.ELEMENT_NODE && !node.hasAttribute('ripple-init') && node.hasAttribute('ripple')) {
node.addEventListener('click', showRipple);
node.setAttribute('ripple-init', '');
}
});
}
}
};
const mutationObserver = new MutationObserver(listener);
mutationObserver.observe(document, { subtree: true, childList: true, attributes: true });
setTimeout(() => {
document.querySelector('button').setAttribute('ripple', '');
let btn = document.createElement('button');
btn.setAttribute('ripple', '');
// btn.setAttribute('class', 'ripple');
btn.innerText = 'SeriousLose SeriousLose';
document.body.appendChild(btn);
}, 2000);
</script>
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交