问题
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
回答1:
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);
}
Here's a js fiddle: http://jsfiddle.net/FcFW2/1/. Run once and then run again. The second time the popup does not show.
回答2:
this should get you started: http://www.quirksmode.org/js/cookies.html
the following examples use the functions declared in the above link.
creating a cookie:
// when the div is clicked
createCookie('hideSuggestionBox', 'true', 1);
reading a cookie:
// when deciding whether to show or hide the div (probably on document ready)
if (readCookie('hideSuggestionBox') === 'true') {
// do not show the box, the cookie is there
} else {
// the cookie was not found or is expired, show the box
}
来源:https://stackoverflow.com/questions/10674611/hide-div-24hr-cookie-javascript