首页 > 解决方案 > 如何使按钮在第一次单击时消失,等待,然后在几秒钟后出现在另一个位置?

问题描述

我创建了一个按钮(#nextbtn),当它被点击时会淡出。我如何让它等待,比如 3 秒,然后在之前的 100 像素以下淡出?并在每次单击时继续执行此操作?这是我到目前为止所拥有的:CSS:

 #nextbtn {
               transition: margin-top 1s, opacity 1s;
                opacity:1;
            }

HTML:

<button id="nextbtn" onclick="nextClicked()">NEXT</button>

JS:

function nextClicked() {
                var next = document.getElementById("nextbtn")
                next.style.opacity = "0"
                next.style.marginTop = "-30px"
            }

标签: javascripthtmlfunctiononclicktransition

解决方案


这是代码:

而不是使用顶部 [位置:相对] 使用边距

    var next = document.getElementById("nextbtn");
var top1 = 0;

function nextClicked() {

next.style.opacity = "0";

setTimeout(()=>{
top1 += 100;
next.style.opacity = "1";
next.style.top = top1 + "px";

},3000);// 3 sec
}
    #nextbtn {
transition: margin-top 1s, opacity 1s;
position: relative;
top: 0px;
}
<button id="nextbtn" onclick="nextClicked()">NEXT</button>


推荐阅读