我在我的网站的单独 .css 文件中有一些 CSS,如下所示:
html {
background: url("images/1080 Native2.jpg") no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
height: 100%;
}
这行得通,我想保持这种风格,但每天都有,根据每月的日期,背景图像会有所不同。我的意图是使用 JS 通过 jQuery 执行此操作,并在一个数组中列出所有文件名,以每月的日期为数组大小的模数来获取要显示的图像。该脚本的部分作用在于它确实为日期获取了正确的文件名,但不知何故它没有将此信息正确写入 html 标记的样式。以下是我当前的 HTML、CSS 和 JS 文件:
HTML (index.php):
<html>
<head>
<title>ChillSpot Alpha-test 1.0.7</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="background.js"></script>
<script type="text/javascript"> $( document ).ready( getImage );</script>
</head>
... (rest of page)
JavaScript (background.js):
<!--
function getImage(){
var myimages=new Array();
//specify images below.
myimages.push("1080pAfrican.jpg");
myimages.push("1080pDragon.jpg");
myimages.push("1080pIndia.jpg");
myimages.push("1080pNativeAmerican.jpg");
myimages.push("1080pNativeAmerican2.jpg");
var len = myimages.length;
var dayOfMonth = new Date().getDate();
var index = dayOfMonth % len;
alert(dayOfMonth + "," + index + "," + myimages[index]);
//document.write("<html style='background: url('images/" + myimages[index] + "') no-repeat center center fixed;'>");
document.getElementsByTagName('html')[0].style.background = 'url("images/' + myimages[index] + '") no-repeat center center fixed;';
}
//-->
CSS(样式.css):
html {
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
height: 100%;
}
我为此使用 jquery-1.11.2.min.js
...我的方法有什么问题?我查了很多关于 javascript 的东西,但我不明白哪里出了问题。我认为这可能与我实际尝试更改 html 标签的“背景”属性有关,但我不确定!
非常感谢!
最佳答案
如果您要使用 jQuery,请也将其用于选择器:)
注意:您可以使用文字数组代替所有推送。
function getImage(){
var myimages=["1080pAfrican.jpg",
"1080pDragon.jpg",
"1080pIndia.jpg",
"1080pNativeAmerican.jpg",
"1080pNativeAmerican2.jpg"];
var len = myimages.length;
var dayOfMonth = new Date().getDate();
var index = dayOfMonth % len;
alert(dayOfMonth + "," + index + "," + myimages[index]);
$('html').css('background-image', 'url("images/' + myimages[index] + '")');
}
关于javascript - 我如何使用 JS 设置 HTML 标签的 “background” 属性,仍然允许 CSS 文件中的其他属性不变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27786592/