繁体   English   中英

重新加载 HTML 浏览器时如何获取随机图像? 使用 javascript、css 和 html

[英]How to get a random image when we reload the HTML browser ? using javascript, css and html

我已经检查了关于这个主题的答案,我尝试了很多,但仍然对我不起作用。 我希望在重新加载 HTML 页面时出现不同的图像。

现在,我有这个非常简单的代码:

HTML:

<head>

<script type="text/javascript" src="../src/index.js"></script>

</head>

<body>
  <div id="container">
    <img id="image_shower_vehicule" class="vehicule" />
  </div>
</body>

</html>

CSS:

#container{
    position:relative;
    width:400px;
    height:400px;
    margin-left: auto;
    margin-right: auto;
    background-color: black;
    z-index:0;
}

.vehicule {
  position:absolute;
  z-index: 1;
}

JS:

var images_array_vehicule = ['vehicule1.png','vehicule2.png','vehicule3.png'];

function getRandomImagevehicule() {

random_index_vehicule = Math.floor(Math.random() * images_array_vehicule.length);
selected_image_vehicule = images_array_vehicule[random_index_vehicule];
document.getElementById('image_shower_vehicule').src =`../public/layers/vehicule/${selected_image_vehicule}`;

}

我有以下文件夹目录...: https://i.stack.imgur.com/xtnML.png

有什么可以帮助我的想法吗?

未来的步骤是对不同的图层做同样的事情,并用 z-index 覆盖选择的图像,但现在我只想在重新加载页面时有一个随机图像。

谢谢你的帮助 !

尝试这个:

调用函数加载:

<body onload="getRandomImagevehicule()">.... </body> 

js代码:

 var images_array_vehicule = ['vehicule1.png','vehicule2.png','vehicule3.png']; function getRandomImagevehicule() { random_index_vehicule = Math.floor(Math.random() * images_array_vehicule.length); selected_image_vehicule = images_array_vehicule[random_index_vehicule]; document.getElementById('image_shower_vehicule').src =`../public/layers/vehicule/${selected_image_vehicule}`; }
 #container { position:relative; width:400px; height:400px; margin-left: auto; margin-right: auto; background-color: black; z-index:0; }.vehicule { position:absolute; z-index: 1; }
 <body onload="getRandomImagevehicule()"> <div id="container"> <img id="image_shower_vehicule" class="vehicule" /> </div> </body>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM