我有一個div
裏面含有大量的大尺寸圖像,並用JavaScript我想插入這個HTML在另一個div
與切換的JavaScript插入HTML與切換
請運行該代碼片段
$(".toggleimages").on("click", function(e) {
e.preventDefault();
var sele = document.querySelector(".bgcontainer");
var colocontainer = '<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>'
sele.insertAdjacentHTML('beforeend', colocontainer)
$(".bgcontainer").slideToggle();
});
li{
list-style-type: none;
font-size: 35px;
cursor: pointer;
}
span{
display: inline-block;
width: 200px;
height: 140px;
background-size: cover;
}
.bgcontainer{
\t 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>
我的問題是,div
使得每次切換按鈕
如何防止HTML插入兩次?或者插入並刪除切換?
爲什麼插入切換?:該div是默認隱藏的,這隻用於如果我想選擇一些背景圖像,所以我覺得它真的很糟糕的頁面速度,如果所有這些大圖像渲染每次你加載頁面,而不是JavaScript我想插入切換HTML。
上點擊修改後的代碼片段,之前更新HTML ....'sele.insertAdjacentHTML( 'beforeend', '')'插入emty HTML ..所以每當你新鮮的HTML附加... –