正如现在的代码,我必须按两次才能使文本出现和消失。
如何才能只按一次按钮就显示“已添加!”文字出现和消失?我希望每次单击按钮时都会发生这种情况。
我尝试过使用 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>
您必须将
display
属性显式设置为 none
。否则,.style.display
将返回空字符串。
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" style="display: none">Added!</p>