前段时间在分析Apple的官网代码时,发现了一个很不错的特效,即网页刷新一次的时候,图片会自动的换一次。比如大家打开www.apple.com/cn/的时候,有时候就会发现网页下面的tile部分会进行图片的轮询切换。这种效果在apple的实现是通过判断来实现的,由于保密性的原因,不能在这里给大家展示源码。
现在我给大家提供另外一种解决思路,即通过localStorage
中的pagecount
属性和页面布局相结合来实现这个效果
首先我们明白localStorage
是HTML 5提供的没有时间限制的数据存储,我们可以利用它来对用户访问页面的次数进行计数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
if (localStorage.pagecount){
localStorage.pagecount=Number(localStorage.pagecount) +1;
}
else{
localStorage.pagecount=1;
}
document.write("刷新页面次数: " + localStorage.pagecount + " time(s).");
var num = localStorage.pagecount;
alert(num);
var b = num % 2;
alert(b);
if(b==0){
bodyBgs[0] = "#first"
}else{
bodyBgs[0] = "#last"
}
</script>
</body>
</html>
通过这种方式,判断用户到底刷了多少次页面。然后刷奇数次页面的时候,显示一张背景图,偶数次页面的时候显示另外一张背景图,完整代码奉上
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
#box li{
list-style: none;
width: 200px;
height: 200px;
margin: auto;
border:3px solid red;
float: left;
}
#first{
display: block;
width: 200px;
height: 200px;
}
#last{
display: block;
width: 200px;
height: 200px;
}
.f-li-f{
background-image: url(images/bg1.jpg);
}
.f-li-l{
background-image: url(images/bg2.jpg);
}
.two-li-f{
background-image: url(images/bg1.jpg);
}
.two-li-l{
background-image: url(images/bg3.jpg);
}
.thr-li-f{
background-image: url(images/bg1.jpg);
}
.thr-li-l{
background-image: url(images/bg4.jpg);
}
.fo-li-f{
background-image: url(images/bg1.jpg);
}
.fo-li-l{
background-image: url(images/bg5.jpg);
}
</style>
</head>
<body>
<div id="box">
<li>
<a href="#" id="first" class="f-li-f"></a>
<a href="#" id="last" class="f-li-l"></a>
</li>
<li>
<a href="#" id="first" class="two-li-f"></a>
<a href="#" id="last" class="two-li-l"></a>
</li>
<li>
<a href="#" id="first" class="thr-li-f"></a>
<a href="#" id="last" class="thr-li-l"></a>
</li>
<li>
<a href="#" id="first" class="fo-li-f"></a>
<a href="#" id="last" class="fo-li-l"></a>
</li>
</div>
</body>
<script>
var class1 = "#first";
var class2 = "#last";
var o = {
message: (function(class1,class2) {
var bodyBgs = [];
if (localStorage.pagecount){
localStorage.pagecount=Number(localStorage.pagecount) +1;
}else{
localStorage.pagecount=1;
}
var num = localStorage.pagecount;
var b = num % 2;
if(b==0){
bodyBgs[0] = class1
}else{
bodyBgs[0] = class2
}
document.write('<style>' + bodyBgs[0] +'{display:none}</style>')
} (class1,class2)),
};
o.message;
</script>
</html>