[英]Set width of a div in respect to height
I have a div #slideshow
with images of 2:1 aspect ratio. 我有一个div
#slideshow
,图像的纵横比为2:1。 So, set height of image I am using jQuery: 因此,设置图像高度我正在使用jQuery:
Note: The Slideshow Div is 100% wide with respect to browser window.
注意:幻灯片Div相对于浏览器窗口为100%宽。 If user makes the browser window, smaller - it is going to be smaller.
如果用户将浏览器窗口缩小,则窗口将变小。
slideWidth();
function slideWidth(){
var width = $("#slideshow").css("width");
var height = (parseInt(width.substr(0,width.length-2)) /3);
$("#slideshow").css("height",height+"px");
}
And, to make the width change dynamically, I use setTimeout: 并且,为了使宽度动态变化,我使用setTimeout:
setInterval(slideWidth,1000);
This is actually working as I want. 这实际上是我想要的。 But I think I am heavily giving high impact on the website by refreshing the function
slidewidth
every second. 但是我认为我
slidewidth
都要刷新一次slidewidth
功能, slidewidth
对网站产生重大影响。
Is this achievable through CSS3? 通过CSS3是否可以实现? Or with jQuery/JS with less Website Impact?
还是使用jQuery / JS对网站的影响较小?
Thank you. 谢谢。 Feel free to comment with new ways/ideas.
随时以新的方式/想法发表评论。
There's a css-only approach using pseudo elements and padding: 有一种使用伪元素和填充的纯css方法:
div {
width: 100%;
position: relative;
background: red;
}
div:before {
display: block;
content: "";
padding-top: 50%;
}
The combination of the pseudo padding-top
can be used to vary between aspect ratios. 伪
padding-top
的组合可用于在宽高比之间变化。
In this case, the 50%
padding is equivalent to aspect ratio of 2:1
在这种情况下,填充率
50%
相当于纵横比为2:1
You should be using jquerys .resize(); 您应该使用jquery .resize(); This adds an event listener waiting for the container to resize.
这将添加一个事件侦听器,以等待容器调整大小。 Ej:
EJ:
$(window).resize(function(){
//do your logic here
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.