我希望在每次刷新时更改我的HTML背景图片。
这是我在CSS中得到的内容。
html {
background-repeat:no-repeat;
background-position:center center;
background-attachment:fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
这是我用JavaScript(在单独的JS文件中)得到的结果:
var totalCount = 6;
function ChangeBackground()
{
var num = Math.ceil( Math.random() * totalCount );
document.body.parentNode.background = 'background/test/'+num+'.jpg';
}
我在HTML末尾调用我的函数:
<script type="text/javascript">
ChangeBackground();
</script>
我无法使用我拥有的javascript代码在html标签上添加背景。是否有其他方法?
我想特别在html标签上设置它,因为我认为那样更好:
我们可以通过CSS纯粹地实现这一点,这要归功于CSS3中的background-size属性。我们将使用html元素(比body更好,因为它始终至少与浏览器窗口的高度相同)。我们在其上设置一个固定和居中的背景,然后使用background-size设置为cover关键字来调整其大小。