javascript - 如何获得包含尺寸的宽度和高度?

标签 javascript jquery css viewport

假设我有以下 html:

html,body{
    height: 100%;
    overflow-y: hidden;
}
div{
    background: url(path) no-repeat center;
    width: 100%;
    height: 100%;
    background-size: contain;
}

demo

这里,background-size是contain,全宽和全高都是100%,但是背景图片的区域没有被div完全覆盖。

那么,有没有什么办法可以得到被覆盖图片的宽高呢?

enter image description here

最佳答案

documentation提到以下关于contain的内容:

This keyword specifies that the background image should be scaled to be as large as possible while ensuring both its dimensions are less than or equal to the corresponding dimensions of the background positioning area.

这将适用于以下代码 (ES6):

function contain({width: imageWidth, height: imageHeight}, {width: areaWidth, height: areaHeight}) {
  const imageRatio = imageWidth / imageHeight;

  if (imageRatio >= areaWidth / areaHeight) {
    // longest edge is horizontal
    return {width: areaWidth, height: areaWidth / imageRatio};
  } else {
    // longest edge is vertical
    return {width: areaHeight * imageRatio, height: areaHeight};
  }
}

console.log(1, contain({width: 15, height: 60}, {width: 20, height: 50}));
console.log(2, contain({width: 15, height: 60}, {width: 50, height: 20}));
console.log(3, contain({width: 60, height: 15}, {width: 20, height: 50}));
console.log(4, contain({width: 60, height: 15}, {width: 50, height: 20}));
console.log(5, contain({width: 40, height: 20}, {width: 50, height: 20}));

根据图像方向(纵向或横向),它首先增加最长的边缘,然后在必要时收缩最短的边缘,同时仍保持纵横比。

关于javascript - 如何获得包含尺寸的宽度和高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24132902/

相关文章:

javascript - ReactJS 是否为服务器端呈现的应用程序两次呈现应用程序? (重复代码)

javascript - 如何链接javascript和html

javascript - 如何在光标到来时将按钮移动到靠近光标的位置并在光标离开时将按钮移动远一点

javascript - 部分 View 复选框在普通 View 中不起作用

javascript - 为什么使用自定义标签创建元素会在 IE9 或 10 的 outerHTML 中添加 xml 命名空间,直到调用 .find() 方法?

javascript - 如何一键禁用 anchor 标记

css - 为什么 Chrome 开发者工具有时不显示 CSS 源代码?

javascript - Bootstrap 崩溃动态 'data-target' 未按预期工作

html - 柔性网格问题嵌套多个柔性方向组合

javascript - HTML 在点击时显示图像