如何在页面刷新时随机交换图像横幅?
how to interchage image banners randomly when page refresh?
这是我的横幅:
请帮我解决这个问题。
我希望当页面加载时,每个横幅都以任何顺序交换位置。
我正在为此使用 apache velocity,但我只想知道如何对其进行编码的逻辑。谢谢
如果您的横幅是图片,您可以创建一个包含所有图片的 JS 数组,randomize 它然后更改您的 img
来源。
例如:
<img id="banner1" src="" />
<img id="banner2" src="" />
<img id="banner3" src="" />
<script>
var images = ["http://exemple.com/banner1", "http://exemple.com/banner2", "http://exemple.com/banner3"];
images = shuffle(images);
$('#banner1').attr('src', images[0]);
$('#banner2').attr('src', images[1]);
$('#banner3').attr('src', images[2]);
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
</script>
这是我的横幅:
请帮我解决这个问题。 我希望当页面加载时,每个横幅都以任何顺序交换位置。
我正在为此使用 apache velocity,但我只想知道如何对其进行编码的逻辑。谢谢
如果您的横幅是图片,您可以创建一个包含所有图片的 JS 数组,randomize 它然后更改您的 img
来源。
例如:
<img id="banner1" src="" />
<img id="banner2" src="" />
<img id="banner3" src="" />
<script>
var images = ["http://exemple.com/banner1", "http://exemple.com/banner2", "http://exemple.com/banner3"];
images = shuffle(images);
$('#banner1').attr('src', images[0]);
$('#banner2').attr('src', images[1]);
$('#banner3').attr('src', images[2]);
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
</script>