JS讓任意圖片垂直水平置中且頁面不滾動

來源:互聯網
上載者:User

標籤:通過   高度   顯示   垂直   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讓任意圖片垂直水平置中且頁面不滾動

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.