[英]Scale div proportionally to fit viewport
我寫了一個小函數,按比例減小div
的大小,直到它的高度與視口相同。 這非常有效。 我有2個問題我想解決
該函數背后的目標是使container
div永遠不會高於視口。 這需要通過設置container
的width
來控制,因為內容是響應的。 為了演示目的,我使用了寬度為100%的簡單圖像。 由於缺乏瀏覽器支持,我沒有使用vh
或vw
。 我需要支持IE8。
function setImageViewPointHeight() {
// get current viewport height
var targetHeight = $(window).height();
// get current container height
var containerHeight = $('.container').height();
// get current container width
var containerWidth = $('.container').width();
// only set width if container is higher than viewport
if (containerHeight > targetHeight) {
// keep reducing container height/width value by 0.1% until target is reached
while (containerHeight > targetHeight) {
containerHeight = containerHeight - (containerHeight * .01);
containerWidth = containerWidth - (containerWidth * .01);
}
// now we have desired calculated width
$('.container').width(containerWidth + 'px');
}
}
考慮到瀏覽器支持,我認為這種方法沒有問題。 從我的角度來看,這看起來很干凈。
要在視口高度減小時修復容器高度調整問題,只需在調用函數時將width
設置為initial
值。
function setImageViewPointHeight() {
$('.container').css('width', 'initial'); <-- add this
var targetHeight = $(window).height();
var containerHeight = $('.container').height();
var containerWidth = $('.container').width();
if (containerHeight > targetHeight) {
while (containerHeight > targetHeight) {
containerHeight = containerHeight - (containerHeight * .01);
containerWidth = containerWidth - (containerWidth * .01);
}
$('.container').width(containerWidth + 'px');
}
}
我會使用vw
vh
CSS單位將div縮放到視口。
https://css-tricks.com/viewport-sized-typography/
IE8不支持它,但你可以找到它的polyfills https://github.com/saabi/vminpoly
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.