这是我想要在页面刷新时更改图像的完整代码。这是我正在使用但不起作用的代码。
<SCRIPT LANGUAGE="JavaScript">
var theImages = new Array()
theImages[0] = 'images/1.png'
theImages[1] = 'images/2.png'
theImages[2] = 'images/3.png'
var j = 0
var p = theImages.length;
var preBuffer = new Array()
for (i = 0; i < p; i++){
preBuffer[i] = new Image()
preBuffer[i].src = theImages[i]
}
var whichImage = Math.round(Math.random()*(p-1));
function showImage(){
if(whichImage==0){
document.write('<a href ="link.html">
<img src="'+theImages[whichImage]+'"');
}
else if(whichImage==1){
document.write('<a href ="link.html">
<img src="'+theImages[whichImage]+'"');
}
else if(whichImage==2){
document.write('<a href ="link.html">
<img src="'+theImages[whichImage]+'"');
}
else if(whichImage==3){
document.write('<a href ="link.html">
<img src="'+theImages[whichImage]+'"');
}
else if(whichImage==4){
document.write('<a href ="link.html">
<img src="'+theImages[whichImage]+'"');
}
}
</SCRIPT>
这是我想要更改图像的html代码。在那里我调用了脚本函数。
<div class="under_header" style="height:600px;margin-top:0px; background:url(<script>showImage();</script>) , url(images/latest_movie/<?php echo $movie_image; ?>) center 76px fixed no-repeat; -moz-background-size:auto, over; background-size:auto, cover;
box-shadow: inset 945px 0px 645px -645px black, inset -945px 0px 645px -645px black;">
</div>
不能将script
标记放在样式属性的CSS字符串中。
在JavaScript中尝试这样的东西,而不是在CSS:中
document.getElementsByClassName("under_header")[0].style.background = "url("+showImage()+") , url(images/latest_movie/<?php echo $movie_image; ?>) center 76px fixed no-repeat";
不知道您是否已经解决了问题,但正如Jacques所说,您调用脚本的方式不起作用。
检查"whichImage"的值是不必要的,你可以这样做:
function showImage() {
$('.under_header').append('<a href ="link.html"><img src="' + theImages[whichImage] + '"></a>');
}
这是一把小提琴,人们喜欢小提琴。https://jsfiddle.net/Sprazer/va9j5sb0/
很抱歉使用jQuery
尝试组合javascript和css的方式是行不通的。以下示例将背景图像随机设置为目标分区。
函数showImage
是在onload
事件上调用的。因此,每次刷新页面时,div都会有不同的背景图像。
使用此示例可以构建页面刷新所需的任何功能。
<html>
<head>
<script language="JavaScript">
var theImages = new Array();
theImages[0] = 'images/1.jpg';
theImages[1] = 'images/2.jpg';
theImages[2] = 'images/3.jpg';
var p = theImages.length;
var whichImage = Math.round(Math.random()*(p-1));
function showImage(){
document.getElementById('myDiv').style.backgroundImage="url('" + theImages[whichImage] + "')";
}
</script>
</head>
<body onload="showImage()">
<div id="myDiv" style="width:300px; height: 200px;" />
</body>
</html>