我有一个隐藏的 div,其中至少包含 +20 个跨度,每个跨度都有一个大尺寸的背景图像,就像这样
此 div 仅隐藏并显示一个按钮,因此使用的背景图像始终在页面加载时加载
$( ".toggleimages" ).on( "click", function(e) {
e.preventDefault();
$(".bgcontainer").slideToggle();
});
li{
list-style-type: none;
font-size: 35px;
cursor: pointer;
}
span{
display: inline-block;
width: 200px;
height: 140px;
background-size: cover;
}
.bgcontainer{
display: none;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="toggleimages"><i class="fa fa-picture-o" aria-hidden="true"></i></li>
<div class="bgcontainer">
<div class="container">
<span class="bgImage">
<span style="background-image: url(https://www.gamewallpapers.com/img_script/wallpaper_dir/img.php?src=wallpaper_destiny_2_02_2560x1440.jpg&height=450&width=800&fill-to-fit);"></span>
</span>
<span class="bgImage">
<span style="background-image: url(https://www.gamewallpapers.com/img_script/wallpaper_dir/img.php?src=wallpaper_skull_and_bones_01_2560x1440.jpg&height=450&width=800&fill-to-fit);"></span>
</span>
</div>
</div>
不要在 dom 元素内提供图像,因此它不会在页面加载时加载它,在单击切换图像时使其可用。
一种方法是:
var imagesArray = [
'https://www.gamewallpapers.com/img_script/wallpaper_dir/img.php?src=wallpaper_destiny_2_02_2560x1440.jpg&height=450&width=800&fill-to-fit',
'https://www.gamewallpapers.com/img_script/wallpaper_dir/img.php?src=wallpaper_destiny_2_02_2560x1440.jpg&height=450&width=800&fill-to-fit'
];
$( ".toggleimages" ).on( "click", function (e) {
e.preventDefault();
$(".bgcontainer .bgImage span").each(function (i) {
$(this).attr('style','background-image: url('+ imagesArray[i] +'));
});
$(".bgcontainer").slideToggle();
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句