当为彼此重叠的多个div单击按钮时才开始CSS动画,可以通过以下步骤实现:
以下是一个示例代码:
HTML:
<div class="overlap-button"></div>
<div class="overlap-button"></div>
<div class="overlap-button"></div>
CSS:
.overlap-button {
width: 100px;
height: 100px;
background-color: blue;
margin: 10px;
}
.overlap-button.animate {
animation: myAnimation 1s infinite;
}
@keyframes myAnimation {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
JavaScript:
const buttons = document.querySelectorAll('.overlap-button');
buttons.forEach(button => {
button.addEventListener('click', () => {
const clickedButtons = Array.from(buttons).filter(btn => btn.classList.contains('clicked'));
if (clickedButtons.length > 1 && checkOverlap(clickedButtons)) {
clickedButtons.forEach(btn => btn.classList.add('animate'));
} else {
buttons.forEach(btn => btn.classList.remove('animate'));
}
button.classList.toggle('clicked');
});
});
function checkOverlap(buttons) {
for (let i = 0; i < buttons.length - 1; i++) {
const rect1 = buttons[i].getBoundingClientRect();
for (let j = i + 1; j < buttons.length; j++) {
const rect2 = buttons[j].getBoundingClientRect();
if (!(rect1.right < rect2.left ||
rect1.left > rect2.right ||
rect1.bottom < rect2.top ||
rect1.top > rect2.bottom)) {
return true;
}
}
}
return false;
}
这段代码会为每个具有"overlap-button"类名的div按钮添加点击事件监听器。当多个按钮被点击且重叠在一起时,它们会添加一个名为"animate"的CSS类名,触发旋转动画效果。当按钮不再重叠或只有一个按钮被点击时,移除"animate"类名,停止动画效果。
请注意,这只是一个示例代码,实际情况中可能需要根据具体需求进行调整和优化。
领取专属 10元无门槛券
手把手带您无忧上云