【问题标题】:How do I make something I click fade out and in before it goes to another website linked in the page?如何使我单击的内容在进入页面中链接的另一个网站之前淡出并淡入?
【发布时间】:2022-01-10 20:00:18
【问题描述】:

所以我正在对这个网站进行编码,并且在它更改为我链接到整个页面的另一个网站之前我想要它做的事情淡出。当它最终进入网站时,它会淡入。

有人知道这个代码吗?

【问题讨论】:

  • 这很难做好,因为你不知道链接的网站需要多长时间才能加载完成。要使用设定的动画时间来近似它,您可以使用 setTimeout()
  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: javascript json fadein fade


【解决方案1】:

您可以为您的淡出设置一个css动画,然后在js中使用setTimeout()来延迟该过程并在动画完成后通过js导航到新页面 (而不是<a> 标签)

function navigate(){

    const element = document.querySelector('.otherWebsite');
    element.classList.add('animation'); // setting the animation class to the element

    setTimeout(() =>{
        location.assign('https://stackoverflow.com')
    } , 3000) // delaying the process of the navigation for 3s (3000ms)

}
.otherWebsite{
    padding: 10px;
    background-color: green;
    color: #fff;
}
.animation{
    animation: fadeout 3s linear 1 forwards;
}

@keyframes fadeout {
    from{
        opacity: 1;
    }
    to{
        opacity: 0;
    }
}
<div class="otherWebsite" onclick="navigate()">Click here</div>

注意:您还可以使用data-href或您喜欢的数据集使js函数灵活用于多个标签

document.querySelectorAll('[data-href]').forEach(element =>{  // looping though all tags with 'data-href' in the page
    // setting an onclick event listener for the element
   element.onclick = () =>{
       element.classList.add('animation') // setting animation class to element
       const link = element.dataset.href || element.getAttribute('data-href'); // getting the link from the 'data-href' attribute
       setTimeout(() => location.assign(link) , 3000) // navigate to a new website after 3s (3000ms)
   }

})
.otherWebsite{
    padding: 10px;
    background-color: green;
    color: #fff;
    margin: 10px 0px;
}
.animation{
    animation: fadeout 3s linear 1 forwards;
}

@keyframes fadeout {
    from{
        opacity: 1;
    }
    to{
     opacity: 0;
    }
}
<div class="otherWebsite" data-href="https://stackoverflow.com">Website (stackoverflow)</div>
<div class="otherWebsite" data-href="https://google.com">Website 2 (google)</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-11
    • 2012-07-19
    相关资源
    最近更新 更多