標籤:通過 高度 顯示 垂直 fse 功能 寬度 瀏覽器 滾動
說一下以前遇到的一個問題:
假設有一張小圖,要實現點擊查看大圖的功能,而這個圖的寬高可能會超過瀏覽器的寬高,這時候我們通過JS來改變圖片的寬高,從而實現圖片在瀏覽器置中顯示且不滾屏。
方法如下:
首先你要給小圖添加一個點擊事件,不多贅述。
showBigImg(e) {
let w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
let h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
if (e.target.naturalHeight && e.target.naturalWidth) {
const naturalHeight = e.target.naturalHeight;
const naturalWidth = e.target.naturalWidth;
const rh = h - naturalHeight;//瀏覽器視圖寬度-圖片寬度=rh
const rw = w - naturalWidth;//瀏覽器視圖高度-圖片高度=rw
if (rh >= 0 & rw >= 0) {//圖片寬高未超出瀏覽器視圖寬高
cimg.style.height = "auto";
cimg.style.width = "auto";
cimg.style.top = rh / 2 + "px";
cimg.style.left = rw / 2 + "px";
} else if (rh >= 0 & rw < 0) {//圖片寬度超出瀏覽器視圖寬度,且高度未超出瀏覽器視圖高度,將圖片的寬度改變為瀏覽器視圖寬度,圖片的寬度等比例縮小
cimg.style.width = w + "px";
cimg.style.height = "auto";
cimg.style.left = 0;
let newrh = h - cimg.offsetHeight;//瀏覽器視圖寬度-改變後圖片高度=newrh
cimg.style.top = newrh / 2 + "px";
} else if (rh < 0 & rw >= 0) {//圖片高度超出瀏覽器視圖高度,且寬度未超出瀏覽器視圖寬度,將圖片的高度改變為瀏覽器視圖高度,圖片的寬度等比例縮小
cimg.style.height = h + "px";
cimg.style.width = "auto";
let newrw = w - cimg.offsetWidth;//瀏覽器視圖寬度-改變後圖片寬度=newrw
cimg.style.left = newrw / 2 + "px";
cimg.style.top = 0;
} else {//圖片寬高均超出瀏覽器視圖寬高,將圖片寬高改變為瀏覽器視圖寬高
cimg.style.width = w + "px";
cimg.style.height = h + "px";
cimg.style.left = 0;
cimg.style.top = 0;
}
}
}
JS讓任意圖片垂直水平置中且頁面不滾動