我有一个JS功能,可以根据body标签显示不同的背景图像。它适用于所有浏览器,但Safari。所有浏览器都会根据类显示正确的图像,但是,IE仅在“else”中显示图像。
我不确定我错过了什么。
<script type="text/javascript">
function loadNextImage() {
if ($("body").hasClass('bodyNormal') === true) {
//get image object
var myImg = document.getElementById('homeImage');
//declare image directory path and image array
var thePath = "images/background/";
var theImages = new Array();
theImages[0] = "home1.jpg";
theImages[1] = "home2.jpg";
theImages[2] = "home3.jpg";
theImages[3] = "home4.jpg";
theImages[4] = "home5.jpg";
//get current cookie value
var currentIndex = parseInt(getCookie());
var imgPath = thePath + theImages[currentIndex];
myImg.src = imgPath;
myImg.alt = theImages[currentIndex];
myImg.title = theImages[currentIndex];
//set next cookie index
currentIndex += 1;
if(currentIndex > (theImages.length - 1)) {
currentIndex = 0;
}
setCookie(currentIndex);
}
else {
//get image object
var myImg = document.getElementById('homeImage');
//declare image directory path and image array
var thePath = "images/m-background/";
var theImages = new Array();
theImages[0] = "m-home.jpg";
theImages[1] = "m-home.jpg";
//get current cookie value
var currentIndex = parseInt(getCookie());
var imgPath = thePath + theImages[currentIndex];
myImg.src = imgPath;
myImg.alt = theImages[currentIndex];
myImg.title = theImages[currentIndex];
//set next cookie index
currentIndex += 1;
if(currentIndex > (theImages.length - 1)) {
currentIndex = 0;
}
setCookie(currentIndex);
}
}
function setCookie(someint) {
var now = new Date();
var addDays = now.getDate() + 7
now.setDate(addDays); // cookie expires in 7 days
var theString = 'imgID=' + escape(someint) + ';expires=' + now.toUTCString();
document.cookie = theString;
}
function getCookie() {
var output = "0";
if(document.cookie.length > 0) {
var temp = unescape(document.cookie);
temp = temp.split(';');
for(var i = 0; i < temp.length; i++) {
if(temp[i].indexOf('imgID') != -1) {
temp = temp[i].split('=');
output = temp.pop();
break;
}
}
}
return output;
}
</script>
显然,没有设置body类,这就是为什么上面的代码不起作用的原因。以下是设置正文类的代码:
<script>
function setStyleForSize() {
if(screen.width > 480) {
document.body.className = "bodyNormal";
}
else {
document.body.className = "bodySmall";
}
}
function addEventHandler(oNode, evt, oFunc) {
if (typeof(window.event) != "undefined")
oNode.attachEvent("on"+evt, oFunc);
else
oNode.addEventListener(evt, oFunc, true);
}
addEventHandler(window, "load", function() { setStyleForSize(); } );
addEventHandler(window, "resize", function() { setStyleForSize(); } );
</script>