正如现在的代码,我必须按两次才能使文本出现和消失。
如何才能只按一次按钮就显示“已添加!”文字出现和消失?我希望每次单击按钮时都会发生这种情况(即使用户在文本消失时单击,它也应该从完全可见开始到消失)。
我尝试过使用 CSS 进行聚焦。我也尝试过重新排列 javascript 代码,以及在 javascript 中插入 while 循环,但我一定做错了什么。
谢谢
function cartAdded() {
var text = document.getElementById("added-notification");
if (text.style.display === "none") {
text.style.display = "block";
} else {
text.style.display = "none";
}
}
.added-fade-out {
opacity: 0;
display: none;
animation: fadeOut 1s ease-out;
}
@keyframes fadeOut {
0% {
opacity: 1;
display: none;
}
50% {
opacity: 0.5;
display: block;
}
100% {
opacity: 0;
display: none;
}
}
<button type='button' onclick="cartAdded()">Click me</button>
<p id='added-notification' class="added-fade-out">Added!</p>
编辑:这是我不知道如何问的问题之一,因为我不知道要使用的术语。后来经过一番查找,找到了更符合我问题的解决方案。
基本上,原来的问题还需要动画在每次点击后重新启动,而不仅仅是在动画结束时重新启动。这段代码与我想要实现的目标更接近(堆栈溢出:每次单击按钮时都应播放动画)
每次点击后都会重播动画:
function showMessage() {
let message = document.getElementById('child');
if (message.classList.contains('d-none')) {
message.classList.remove('d-none');
}
// message.classList.add('d-none');
message.style.animation = 'none';
message.offsetHeight;
message.style.animation = null;
}
.parent {
position: relative;
width: 600px;
height: 150px;
}
@keyframes msgSuccess {
50% {
opacity: 1;
}
99% {
opacity: 0;
}
100% {
opacity: 0;
display: none;
}
}
.child {
position: absolute;
width: 100%;
height: 50px;
animation-name: msgSuccess;
animation-duration: 1s;
opacity: 0;
}
.d-none {
display: none;
}
<button onclick="showMessage()">Click Me</button>
<div id="parent" class="parent">
<div id="child" class="child d-none">Message</div>
</div>
animationend
事件来删除您的 淡出
const
notificationButton = document.querySelector('#notification-btn')
, pNotificationText = document.querySelector('#notification-text')
;
notificationButton.addEventListener('click', () =>
{
notificationButton.disabled = true;
pNotificationText.classList.replace('noDisplay','show-fade-out')
})
pNotificationText.addEventListener('animationend', () =>
{
notificationButton.disabled = false;
pNotificationText.classList.replace('show-fade-out','noDisplay')
})
.noDisplay {
display: none;
}
.show-fade-out {
animation: fadeOut 1s ease-out forwards;
}
@keyframes fadeOut {
100% { opacity: 0; }
}
<button id="notification-btn">Click me</button>
<p id='notification-text' class="noDisplay" > Added! </p>
您必须首先将
display
属性显式设置为 none
。否则,text.style.display
将返回空字符串。
var text = document.getElementById("added-notification");
text.addEventListener('animationend', () => {
text.style.display = "none"
})
function cartAdded() {
if (text.style.display === "none") {
text.style.display = "block";
} else {
text.style.display = "none";
}
}
.added-fade-out {
opacity: 0;
display: none;
animation: fadeOut 1s ease-out;
}
@keyframes fadeOut {
0% {
opacity: 1;
}
50% {
opacity: 0.5;
}
100% {
opacity: 0;
}
}
<button type='button' onclick="cartAdded()">Click me</button>
<p id='added-notification' class="added-fade-out" style="display: none">Added!</p>