如果网站可见,如何触发动画?

时间:2018-11-03 05:45:21

标签: jquery html css animation

我一直在为自己的网站使用W3.CSS Animations动画来获得简单的“淡入淡出”效果,但我意识到它们是在页面加载时触发的,如果您将网站置于后台,则动画无论如何都会触发,因此很容易错过了,有没有一种方法可以仅在窗口可见时触发动画,例如以下站点:https://www.aristidebenoist.com/

我在Jquery上使用了一些技巧,但是您需要将其悬停才能正常工作,所以我对使用其他方法完全不信服吗?

$(document).ready(function(){
$(document).hover(function(){
    $("body").css("display", "block").fadeIn(2000);
    });
    });

或者有一种方法可以在屏幕上显示div时触发动画(不涉及滚动)?

4 个答案:

答案 0 :(得分:2)

您需要Document.hasFocus()。点击下面的iframe以设置焦点

function checkPageFocus()
{
  if (document.hasFocus())
  {
    $("#showMe").fadeIn(1200);
    console.log("The document has the focus.");
  }
  else
  {
    console.clear()
    console.log("The document doesn't have the focus, click me!");
    setTimeout(checkPageFocus, 500);
  }
}
setTimeout(checkPageFocus, 500);
#showMe{display:none;width:300px;height:200px;background:yellow}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="showMe">The document has the focus.</div>

答案 1 :(得分:2)

  • jQuery.ready / DOMContentLoaded在所有HTML都准备好与之交互时发生,但通常在将其呈现到屏幕上之前发生。
  • 当所有HTML均已加载且所有子资源(如图像)均已加载时,就会发生load事件。
  • 使用setTimeout允许在代码运行之前呈现页面。
  

您应该在文档完全加载后运行动画   &render,不是最好的方法,但是您可以将setTimeout函数设置为   文档末尾至少300ms

所有内容加载完毕(未呈现)

window.addEventListener('load', function(){ 
    // Everything has loaded! 
});

如果您正在使用图片

document.querySelector('img.my-image').addEventListener('load', function(){
   // The image is ready!
});

在实际显示当前更改后运行

setTimeout(function(){
   // Everything will have rendered here
});

来源:eager.io/blog

答案 2 :(得分:1)

$(function(){
    $("body").css("display","block").fadeIn(2000);
});

$(document).ready(function(){
    $("body").css("display","block").fadeIn(2000);
});

答案 3 :(得分:0)

尝试

$(window).on("load", function() {
  //your code
});