html
<imgclass="img img-toggle"src="xxx.jpg"alt="">
CSS
<style>
? ? .overlay {
? ? /*背景色,透明度*/
? ? ? ? background-color: rgba(24 23 23 / 0.85);
? ? ? ? position: fixed;
? ? ? ? top: 0;
? ? ? ? left: 0;
? ? ? ? width: 100%;
? ? ? ? height: 100%;
? ? ? ? z-index: 100;
? ? ? ? /*由于圖片高度可能超出了頁面,需要設(shè)置滾動條*/
? ? ? ? overflow: auto;
? ? ? ? display: flex;
? ? ? ? justify-content: center;
? ? ? ? align-items: center;
? ? ? ? flex-direction: row;
? ? }
? ? .overlayimg {
? ? ? ? width: 40%;
? ? ? ? /*寬度*/
? ? ? ? height: auto;
? ? ? ? /*高度自動*/
? ? }
? ? /* 鼠標(biāo)移動到圖片變?yōu)榉糯箸R */
? ? .img-toggle {
? ? ? ? cursor: -webkit-zoom-in;
? ? ? ? cursor: zoom-in;
? ? }
? ? .img{
? ? ? ? float: left;
? ? ? ? width: 100px;
? ? ? ? height: 100px !important;
? ? ? ? padding: 10px;
? ? ? ? object-fit: cover;
? ? ? ? border-radius: 20px;
? ? }
</style>
JS
//該方法在圖片列表加載完成以后執(zhí)行:
window.onload = function () {
addExpand();
}
/*循環(huán)給class='img-toggle'圖片的onclick和onckeydown指定了expandPhoto方法痘番,
該方法實現(xiàn)了點(diǎn)擊圖片放大的功能:*/
function addExpand() {
var imgs = document.getElementsByClassName("img-toggle");
imgs[0].focus();
for (var i = 0; i < imgs.length; i++) {
imgs[i].onclick = expandPhoto;
imgs[i].onkeydown = expandPhoto;
}
}
/*expndPhoto創(chuàng)建了一個id="overlay"厅篓,class="overlay"的div,
再給div創(chuàng)建了一個id="expand"徘意,class="overlayimg"的img標(biāo)簽懂昂,
overlay和overlayimg類選擇器定義如下:*/
function expandPhoto() {
var overlay = document.createElement("div");
overlay.setAttribute("id", "overlay");
overlay.setAttribute("class", "overlay");
document.body.appendChild(overlay);
var img = document.createElement("img");
img.setAttribute("id", "expand")
img.setAttribute("class", "overlayimg");
img.src = this.getAttribute("src");
document.getElementById("overlay").appendChild(img);
img.onclick = restore;
}
/*給創(chuàng)建的img標(biāo)簽的onclick指定了restore方法,該方法實現(xiàn)了點(diǎn)擊大圖回到圖片列表的功能*/
function restore() {
document.body.removeChild(document.getElementById("overlay"));
document.body.removeChild(document.getElementById("expand"));
}