[英]change the image after refresh the page
我想在刷新頁面后更改圖像,但是它不起作用
這是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>
這是html的主要部分
<nav class="spot" onload="changeImage()">
<h1>SPOTLIGHT</h1>
<a href="play.html"><img id="spotlight" width="1000" height="600" alt=""></a>
</nav>
<nav>
元素不支持onload
屬性。 在<body>
上嘗試
您的圖像數組中也存在語法錯誤。 不必要的分號。
請參見下面的工作示例:
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" ]; function changeImage(){ var size=theImages.length; var x = Math.floor(size*Math.random()) document.getElementById("spotlight").src = theImages[x]; }
<body onload="changeImage()"> <nav class="spot" > <h1>SPOTLIGHT</h1> <a href="play.html"><img id="spotlight" width="1000" height="600" alt=""></a> </nav> </body>
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" ]; function changeImage(){ var size=theImages.length; var x = Math.floor(size*Math.random()) document.getElementById("spotlight").src = theImages[x]; }
<body onload="changeImage()"> <nav class="spot"> <h1>SPOTLIGHT</h1> <a href="play.html"><img id="spotlight" width="1000" height="600" alt=""></a> </nav>
單獨的CSS
, JS
和HTML
。
將變量聲明為
var theImages = [],
size, x;
刪除onload()函數。 如下重寫隨機函數。
x = Math.floor(Math.random()*大小);
Math.random()返回介於0(含)和1(不含)之間的浮點偽隨機數。 在這里Math.floor總是返回0,1,2之間的值。
如下重寫代碼。
size = theImages.length;
x = Math.floor(Math.random() * size);
document.getElementById("spotlight").src = theImages[x];
var theImages = [], size, x; theImages = [ "https://www.w3schools.com/w3css/img_car.jpg", "https://www.w3schools.com/css/paris.jpg", "https://www.w3schools.com/css/trolltunga.jpg" ]; size = theImages.length; x = Math.floor(Math.random() * size); document.getElementById("spotlight").src = theImages[x];
#spotlight { width: 1000px; height: 600px; }
<h1>SPOTLIGHT</h1> <a href="#"><img id="spotlight" alt=""></a>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.