jQuery - 在一个会话中仅运行一次动画

jQuery - Runs Animation Only Once In a Session

本文关键字:运行 动画 一次 一个 jQuery 会话      更新时间:2023-09-26

我正在使用以下函数在页面首次加载时启动动画。而且它工作正常。

function checkAnimation_ss() {
    var $elem = $('.ss');
    // If the animation has already been started
    if ($elem.hasClass('icon_start')) return; //or same session??
    if (isElementInViewport($elem)) {
        // Start the animation
        $elem.addClass('icon_start');
    }
}

我的问题是,当我导航到另一个页面然后点击浏览器的"后退"但键时,动画会再次开始。

有没有办法让动画在一个会话中只运行一次?我知道我需要使用jquery.cookie.js在某种程度上,我只是想不通?

非常感谢您的帮助

是的,您可以将cookie与jquery.cookie一起使用.js在这种情况下,您需要执行类似于以下内容的操作:

 function checkAnimation_ss() {
var cookieValue = $.cookie("animation");
if(cookieValue == 1)
{}
else
{
    var $elem = $('.ss');
    // If the animation has already been started
    if ($elem.hasClass('icon_start')) return; //or same session??
    if (isElementInViewport($elem)) {
        // Start the animation
        $elem.addClass('icon_start');
        $.cookie("animation", 1);
    }
}}

当然,如果您的网站使用它,您也可以使用 php 解决它。在这种情况下,您可以执行以下操作:

<?php session_start(); $_SESSION['animation'] = 1; ?>

然后:

function checkAnimation_ss() {
<?php 
    if($_SESSION['animation'] == 1)
    {}
    else
    {
?>
    var $elem = $('.ss');
    // If the animation has already been started
    if ($elem.hasClass('icon_start')) return; //or same session??
    if (isElementInViewport($elem)) {
        // Start the animation
        $elem.addClass('icon_start');
        $.cookie("animation", 1);
    }
<?php 
}
?>}

最终代码 ...

function checkAnimation_ss() {
    var cookieValue = $.cookie("animation");
    var $elem = $('.ss');
    if(cookieValue == 1){
        $elem.addClass('icon_visible');
    }else{
      // If the animation has already been started
      if ($elem.hasClass('icon_start')) return;
      if (isElementInViewport($elem)) {
          // Start the animation
          $elem.addClass('icon_start');
          $.cookie("animation", 1);
      }
    }
}