Javascript 刷新页面后更改图像

Javascript 刷新页面后更改图像,javascript,html,Javascript,Html,我想在刷新页面后更改图像,但它不起作用 下面是javascript部分 <script> var theImages = [ "../images/casblanca.jpg", "../images/casblanca2.jpg", "../images/spot.jpg"; ]; function changeImage(){ var size=theImages.length; var x = Math.floor(siz

我想在刷新页面后更改图像,但它不起作用

下面是javascript部分

<script>
  var theImages = [
      "../images/casblanca.jpg",
      "../images/casblanca2.jpg",
      "../images/spot.jpg";
  ];
  function changeImage(){
  var size=theImages.length;
  var x = Math.floor(size*Math.random())
  document.getElementById("spotlight").src = theImages[x];
}
</script>

变量图像=[
“./images/casblanca.jpg”,
“./images/casblanca2.jpg”,
“./images/spot.jpg”;
];
函数changeImage(){
变量大小=图像长度;
var x=Math.floor(大小*Math.random())
document.getElementById(“spotlight”).src=theImages[x];
}
这是html的主要部分

  <nav class="spot" onload="changeImage()">
      <h1>SPOTLIGHT</h1>
      <a href="play.html"><img id="spotlight" width="1000" height="600" alt=""></a>
    </nav>

聚光灯

元素上不支持
onload
属性。在

图像数组中还有一个语法错误。不必要的分号

请参见下面的工作示例:

var theImages=[
"https://dummyimage.com/1000x600/000/fff&text=Image+1",
"https://dummyimage.com/1000x600/000/f0f&text=Image+2",
"https://dummyimage.com/1000x600/000/ff0&text=Image+3"
];
函数changeImage(){
变量大小=图像长度;
var x=Math.floor(大小*Math.random())
document.getElementById(“spotlight”).src=theImages[x];
}

聚光灯
1)您正在使用和额外分号(;)

“./images/spot.jpg”

在最后一张图片的末尾。继续删除它

2)在body标签中使用onload事件。

这里有一个有效的解决方案。希望有帮助

var theImages=[
"http://media.caranddriver.com/images/media/51/25-cars-worth-waiting-for-lp-ford-gt-photo-658253-s-original.jpg",
"https://carfromjapan.com/wp-content/uploads/2016/10/5-Best-Rated-Cars-of-2016.jpg",
"https://i.ytimg.com/vi/TzcS7Mcq2oA/maxresdefault.jpg"
];
函数changeImage(){
变量大小=图像长度;
var x=Math.floor(大小*Math.random())
document.getElementById(“spotlight”).src=theImages[x];
}

聚光灯

分开
CSS
JS
HTML

宣布变量为

var theImages = [],
  size, x;
删除onload()函数。 重写随机函数,如下所示

size = theImages.length;
x = Math.floor(Math.random() * size);
document.getElementById("spotlight").src = theImages[x];
x=数学地板(数学随机()*尺寸)

返回介于0(包含)和1(排除)之间的浮点伪随机数。 此处始终返回0,1,2之间的值

按如下所示重写代码

size = theImages.length;
x = Math.floor(Math.random() * size);
document.getElementById("spotlight").src = theImages[x];
var theImages=[],
尺寸,x;
图像=[
"https://www.w3schools.com/w3css/img_car.jpg",
"https://www.w3schools.com/css/paris.jpg",
"https://www.w3schools.com/css/trolltunga.jpg"
];
大小=图像长度;
x=数学地板(数学随机()*尺寸);
document.getElementById(“spotlight”).src=theImages[x]
#聚光灯{
宽度:1000px;
高度:600px;
}
聚光灯