隐藏 div 24hr cookie javascript? [英] Hide div 24hr cookie javascript?

查看:20
本文介绍了隐藏 div 24hr cookie javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个简单的 JavaScript 代码,它可以让我在点击特定的 div 元素一段时间后隐藏它.为了提供更多信息,我在加载主页时会出现一个建议框.我想要的是当点击 div 关闭按钮时,它会设置一个 cookie 以保持框 div 关闭 24 小时(1 天).简单的说,当div关闭按钮被按下时,盒子div隐藏24小时.注意:我有一个 javascript,它允许关闭按钮关闭框,但它会在每次刷新时加载.

I would like a simple JavaScript code that will allow me to hide a certain div element when clicked for a predefined amount of time. To be a little more informative, I have a suggestions box that appears when the home page is loaded. What I would like is when the div close button is clicked it sets a cookie to keep the box div closed for 24 hours (1day). Simply said, when the div close button is pressed, the box div is hidden for 24 hours. Note: I have a javascript that allows the close button to close the box but it will load every refresh.

http://i.stack.imgur.com/du1pA.jpg

推荐答案

虽然 T.J.Crowder 在他的评论中是正确的,stackoverflow 不是用来编写代码的......我为你写了一些代码.这是使用 jQuery 的解决方案.在其中,您将使用 <div id="popupDiv">...</div> 作为消息,并在其中使用 id 为close"的链接来关闭 div.

Although T.J. Crowder is right in his comment that stackoverflow is not here for writing your code... I wrote some code for you. Here's a solution using jQuery. In it you'd use a <div id="popupDiv">...</div> for the message and a link in it with id "close" to close the div.

$(document).ready(function() {

  // If the 'hide cookie is not set we show the message
  if (!readCookie('hide')) {
    $('#popupDiv').show();
  }

  // Add the event that closes the popup and sets the cookie that tells us to
  // not show it again until one day has passed.
  $('#close').click(function() {
    $('#popupDiv').hide();
    createCookie('hide', true, 1)
    return false;
  });

});

// ---
// And some generic cookie logic
// ---
function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

function eraseCookie(name) {
  createCookie(name,"",-1);
}

这是一个 js 小提琴:http://jsfiddle.net/FcFW2/1/.运行一次,然后再次运行.第二次没有显示弹出窗口.

Here's a js fiddle: http://jsfiddle.net/FcFW2/1/. Run once and then run again. The second time the popup does not show.

这篇关于隐藏 div 24hr cookie javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆