我正在使用显示背景图像的超大屏幕来分解文本较多的页面。我有一个文件夹,我在其中放置了几个背景图像,并使用 javascript 从该文件夹中提取图像以用作背景图像。我从这个 stackoverflow 问题中得到了灵感:Random image on page load as Jumbotron background
它工作正常,因为在每个页面加载后都会显示另一个图像。但是,所有超大屏幕都获得相同的图像。我实际上希望这些超大屏幕显示文件夹中的不同背景图像。
有没有办法做到这一点?我可以添加更多的类,让 js 为每个类提取不同的图像。但这对我来说似乎不干净简洁。
附注我无法将带有背景图片的文件夹添加到片段中。
$(document).ready(function() {
var images = ['background-img_1.webp', 'background-img_2.webp', 'background-img_3.webp', 'background-img_4.webp', 'background-img_5.webp'];
$('.jumbotron-fluid').css({
'background-image': 'url(../_assets/img/background-img/' + images[Math.floor(Math.random() * images.length)] + ')'
});
});
.jumbotron {
padding: 1.875rem;
margin: 1.875rem 0;
border-radius: 0;
border: none
}
background-color: grey;
color: black;
}
.jumbotron-fluid {
margin: 0;
border-radius: 0;
background: ;
background-repeat: no-repeat;
background-position: center;
background-attachment: fixed;
background-size: cover;
height: 400px;
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-+sLIOodYLS7CIrQpBjl+C7nPvqq+FbNUBDunl/OZv93DB7Ln/533i8e/mZXLi/P+" crossorigin="anonymous"></script>
<div class="jumbotron jumbotron-fluid my-5">
<div class="container">
</div>
</div>
$(document).ready(function() {
var images = ['background-img_1.webp', 'background-img_2.webp', 'background-img_3.webp', 'background-img_4.webp', 'background-img_5.webp'];
$('.jumbotron-fluid').each(function() {
var randomImage = images[Math.floor(Math.random() * images.length)];
$(this).css({
'background-image': 'url(../_assets/img/background-img/' + randomImage + ')'
});
});
});
使用此代码,每个超大屏幕将从图像数组中随机选择不同的背景图像。请注意,由于随机选择,两个或多个超大屏幕仍然有可能具有相同的背景图像。