我有一个特别的页面是一个网站的一部分;它是直接在HTML编码。我有四个图片,并想显示它们的一个随机在一个特定的地方,页面上的每个网页被人装时间。
我已经试过无数的例子;似乎最符合逻辑的,以我的人是有,将1-4返回一个随机整数的函数,然后我可以简单地把
因此,如果功能发生了返回“2”时,将执行将被给我HTML
我发现,都应该提供一个随机的0,1,2,或3的功能,但我不能让这种方式工作。我不是编程高手,虽然我在简单的HTML相当不错。
你可以创建一个你想使用,然后从这个阵列选择一个随机图象,一旦DOM加载它显示你的HTML图像阵列。
见下面例子:
const images = ["https://images.unsplash.com/photo-1512453979798-5ea266f8880c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1000&q=80",
"https://images.unsplash.com/photo-1493612276216-ee3925520721?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80",
"https://images.unsplash.com/photo-1519834785169-98be25ec3f84?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80"
];
document.addEventListener('DOMContentLoaded', _ => {
const randImageIndex = ~~(Math.random() * images.length);
document.getElementById('randImg').src = images[randImageIndex];
});
img {
width: 50%;
height: auto;
}
<h1>My random image website</h1>
<h3>Take a look around</h3>
<img id="randImg" src="" alt="Random image" />
<p>This is some text</p>
如果你在你的HTML一个形象,你想随机,如果你想你的随机可以使用下面的多张图片,只给你想随机化类randImg
图像以上只适用:
const images = ["https://images.unsplash.com/photo-1512453979798-5ea266f8880c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1000&q=80",
"https://images.unsplash.com/photo-1493612276216-ee3925520721?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80",
"https://images.unsplash.com/photo-1519834785169-98be25ec3f84?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80"
];
document.addEventListener('DOMContentLoaded', _ => {
[...document.getElementsByClassName('randImg')].forEach(e => {
const randImageIndex = ~~(Math.random() * images.length);
e.src = images[randImageIndex];
});
});
img {
width: 50%;
height: auto;
}
<h1>My random image website</h1>
<h3>Take a look around</h3>
<img class="randImg" src="" alt="Random image" />
<p>This is some text1</p>
<img class="randImg" src="" alt="Random image" />
<p>This is more text2</p>
<img class="randImg" src="" alt="Random image" />