zoukankan      html  css  js  c++  java
  • JS让任意图片垂直水平居中且页面不滚动

     说一下以前遇到的一个问题:

           假设有一张小图,要实现点击查看大图的功能,而这个图的宽高可能会超过浏览器的宽高,这时候我们通过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;
    }
    }
    }
  • 相关阅读:
    11. Container With Most Water
    9. Palindrome Number
    375. 猜数字大小 II leetcode java
    leetcode 72 编辑距离 JAVA
    73. 矩阵置零 leetcode JAVA
    快速排序 JAVA实现
    63. 不同路径 II leetcode JAVA
    重写(override)与重载(overload)
    62 不同路径 leetcode JAVA
    leetcode 56 合并区间 JAVA
  • 原文地址:https://www.cnblogs.com/Man-Dream-Necessary/p/7000798.html
Copyright © 2011-2022 走看看