我希望下面的代码只在网站首次加载时执行一次。 我尝试使用cookies和sessionstorage。但我从未找到合适的解决方案。也许这是错的。有没有人知道如何用会话存储解决这个问题?我从来没有做过任何事情。也许是这样的? :
if (!sessionStorage.alreadyClicked) {
$('#my_div');
sessionStorage.alreadyClicked = 1;
}
任何帮助将不胜感激。谢谢。
var my_div;
topIgnore = 100; // (in pixel units) used for function ignoreTop
window.onload = function() {
my_div = document.getElementById('my_div');
var my_div_style = window.getComputedStyle(my_div);
var width_div = parseInt(my_div_style.width, 10); // remove 'px' from string
var height_div = parseInt(my_div_style.height, 10);
// make sure the property exists, else you can get a NaN
my_div.style.left = 0;
my_div.style.top = 0;
// event
window.onmousemove = function(e) {
// my_div.innerHTML = e.pageX +' - '+ (leftBorder + width_div) +' - '+ width_div;
cursorIsInsideDiv(e);
}
// TO DO: feel free to make similar functions for left/right/bottom
// removes the first 100px
function ignoreTop(top) {
if(top < topIgnore) {
return topIgnore;
}
return top;
}
function cursorIsInsideDiv(e) {
var leftBorder = parseInt(my_div.style.left, 10); // remove 'px' from string
var topBorder = parseInt(my_div.style.top, 10);
// move left
if( e.pageX < leftBorder ) {
my_div.style.left = e.pageX + 'px';
}
// move right
else if( e.pageX > (leftBorder + width_div)) {
my_div.style.left = (e.pageX - width_div ) + 'px';
}
// move up
if( e.pageY < topBorder ) {
var top = e.pageY ;
top = ignoreTop(top);
my_div.style.top = top + 'px';
}
// move down
else if( e.pageY > (topBorder + height_div)) {
my_div.style.top = (e.pageY - height_div ) + 'px';
}
}
}
&#13;
#my_div {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
#my_div {
width: 300px;
height: 150px;
background: #ff0000;
position: absolute;
}
&#13;
<div id="my_div">
<h2>Newsletter</h2>
Name: <input type="text" name="fullname"><br>
Email: <input type="text" name="email"><br>
</div>
&#13;
答案 0 :(得分:0)
使用JS设置cookie:
document.cookie = "alreadyClicked=1; expires=Fri, 13 Jan 2017 20:00:00 UTC";
然后,你可以通过定义一个函数来检查它是否存在以找到值(来自http://www.w3schools.com/js/js_cookies.asp):
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
if (getCookie("alreadyClicked") == "1") {
// do stuff if already clicked
} else {
// prompt for click?
}
答案 1 :(得分:0)
我刚刚插入了代码。有效。纠正了这是否错误。
if (!sessionStorage.alreadyClicked) {
$('#my_div');
sessionStorage.alreadyClicked = 1;
}