当我使用这个代码时,标题没有显示任何图像,我不知道我做错了什么,这只是给我带来麻烦的代码我不会错过任何高于或低于它的东西。
<script>
var image = new Array ();
image[0] = "header1.png";
image[1] = "header2.png";
image[2] = "header3.png";
image[3] = "header4.png";
var size = image.length
var x = Math.floor(size*Math.random())
$('#random').attr('src',image[x]);
</script>
<div class="header-img background-cover" style="background-image: url('random');">
答案 0 :(得分:7)
你的问题:
更好的方法是直接设置“background-image”样式属性。像这样:
<div id="header-image" class="header-img background-cover">
<script>
// this now executes after the div has rendered
var image = new Array ();
image[0] = "header1.png";
image[1] = "header2.png";
image[2] = "header3.png";
image[3] = "header4.png";
var size = image.length
var x = Math.floor(size*Math.random())
var backgroundImageFile = image[x]; // 'header1.png'
var backgroundImageUrl = "url('" + backgroundImageFile + "')"; // url('header1.png')
$('#header-image').css('background-image', backgroundImageUrl);
</script>