【问题标题】:JavaScript to hide a div onload after 5 seconds per cookieJavaScript 在每个 cookie 5 秒后隐藏 div 加载
【发布时间】:2018-02-01 11:02:21
【问题描述】:

我正在 Bootstrap 中开发一个网站,需要显示横幅/DIV 5 秒,然后淡出/隐藏,但只需要每个用户/cookie 会话显示一次。有任何想法吗?我在这里看到过类似的解决方案,但只满足了我一半的要求。

【问题讨论】:

  • 您现有的代码在哪里?不应该那么难。只需检查是否存在特定 cookie,创建它,然后显示横幅,然后隐藏它。
  • 道歉:JS = HTML =

    Banner with text

    我是写JS的新手,所以我不知道如何“创建它”,等等。
  • edit您的问题并提供minimal reproducible example
  • 用 cookie 表示你已经展示过了?

标签: javascript html cookies hide seconds


【解决方案1】:

会话存储在服务器端,您不能使用 JavaScript 对其进行修改。会话可能包含敏感数据

请将此代码放在 html 页面的 head 部分。 虽然它不是在 javascript 中执行此操作的最佳方法,而是进入后端并使用 ajax 检查会话。

此 cookie 将存在 2 天

您可以使用 document.cookie 修改 cookie。

<script>
 $(window).on("load", function(){                     // Handler when all assets (including images) are loaded
  var check = getCookie("firsttime");

  if (check == ""){
      var x = document.getElementById("myDIV");     //Suppose the  div you want to hide has id of myDiv , you can place anything you want  
      x.style.display = "block";
      setTimeout(fadeout,5000);
      var d = new Date();
      var expirydate = 2;
      d.setTime(d.getTime() + (expirydate*24*60*60*1000));
      var expires = "expires="+ d.toUTCString();
      document.cookie ="firsttime=no";            //now after the division is hidden cookie value is set so that we could check next day


   } 

   function fadeout() {               //This function will be called after 5 second and it will hide it and will be called if cookie value isnot set 
      var x = document.getElementById("myDIV");  
      x.style.display = "none";
     }  
  });
</script>

【讨论】:

  • 第一次使用的 ref 是做什么用的?我是用 myDIV 替换还是 JS 第一次需要?我遇到了问题,它显示正常,但 5 秒后没有消失。
  • 只有问题在 5 秒后没有消失吗???所有其他事情都根据您的需要??
  • 是的,'myDIV' 使用此 JS 代码显示正常,但 5 秒后不会淡出。你能帮忙吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-26
  • 1970-01-01
  • 1970-01-01
  • 2015-03-11
  • 2012-05-27
相关资源
最近更新 更多