ccs3属性backgroundsize:覆盖机制

时间:2014-08-01 11:54:11

标签: javascript jquery css3 math

我使用了背景:覆盖图像,它完美地完成了工作,但问题是如何获得图像尺寸,这对于任何屏幕尺寸都是如此。

我想计算得到图像渲染的高度和宽度,我有原始图像的高度和宽度,屏幕尺寸与我

1 个答案:

答案 0 :(得分:1)

var screenWidth = 1366; //width of screen or element need to show
var screenHeight = 768;//heightof screen or element need to show
var originalImageWidth = 800; // original image width
var originalImageHeight = 600; // original image height

var backgroundHeight,backgroundWidth;

//default scale by height of screen 
backgroundHeight = screenHeight ;
backgroundWidth= backgroundHeight * originalImageWidth / originalImageHeight;
if ((screenWidth - backgroundWidth) > 0) {//if width of scale images is smaller screen show, begin scale by width
    backgroundWidth = screenWidth;
    backgroundHeight = screenWidth * originalImageHeight / originalImageWidth;
}

然后使用css background-size percent

$(element).css({"background-size":(backgroundWidth+"px"+" "+backgroundHeight+"px")});