简体   繁体   English

如何获取包含大小的宽度和高度?

[英]How to get contain size width and height?

Suppose I have the following html:假设我有以下 html:

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

demo演示

Here, the background-size is contain and is full width and height of 100% but the area of background image is not fully covered by the div.在这里,背景大小是包含并且是全宽和全高的 100% 但背景图像的区域没有被 div 完全覆盖。

So, is there any way to get the width and height of the covered image?那么,有没有什么办法可以得到覆盖图像的宽度和高度呢?

在此处输入图片说明

The documentation mentions the following about contain :文件提到了以下有关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.该关键字指定背景图片在确保其尺寸小于或等于背景定位区域的对应尺寸的情况下,应缩放到尽可能大。

That would work out to the following code (ES6):这将适用于以下代码(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}));

Depending on the image orientation (portrait or landscape) it grows the longest edge first, then shrinks the shortest edge where necessary while still preserving the aspect ratio.根据图像方向(纵向或横向),它首先增加最长的边缘,然后在必要时缩小最短的边缘,同时仍保持纵横比。

Edit::编辑::

var width = $('.demo').width(); //demo is div class name
var height = $('.demo').height();

// if width > height
var imgWidth = width > height ? actualImgWidth/actualImgHeight * height : width;
//if width < height
var imgHeight = height > width ? actualImgHeight/actualImgWidth * width : height;

Use below CSS :使用以下 CSS :

div{
    background: url("Your Image Path") no-repeat;
    width: 100%;
    height: 100%;
    background-position: center;
    background-size: 100% auto;
  }

use this,will work 用这个,会起作用

<script>
$(function() {

 var width=$(".divmenu").width();   //get width and height of div
var height= $(".divmenu").height(); 


$(".divmenu").css('background-size',width ,height);//add width,height into background-size





}); 
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM