簡體   English   中英

如何根據瀏覽器重新設置沿div寬度自動調整div高度

[英]How to adjust div height automatically along the div width according to resiging of browser

我正在努力使網站具有響應能力。 我已經為所有div使用了自動高度。 但是,對於特定的div,我必須對所有大小的瀏覽器使用固定的高度。 但是,我不想自動/動態地對每個尺寸的設備/瀏覽器在媒體查詢中使用高度設置,而是要這樣做。 可能是javascript / jQuery可以做到。 但是,我對javascript / jQuery的了解不多。 所以,我需要你的幫助。 我的容器div的最大寬度:1280px; 我有一個名為“ #artwork”的子div,其初始尺寸為:1065 * 695px。 以base為容器div的最大寬度和#artwork div的初始高度,我想為每次調整瀏覽器大小時為#artwork賦予自動高度。

我不能給“ #artwork”高度:自動,因為在“ #artwork” div上有很多大圖像。 但是,通過javascript,只有一個圖像可以正常顯示,並且通過向下滾動,人們可以看到一個下一幅圖像。 如果我給定height:auto或對“ #artwork”使用最小高度,則會顯示所有圖像。 我已經通過媒體查詢將“ artwork” div高度手動設置在不同類型的css文件中。 但是,我想自動執行此操作,因此該比率非常適合每種設備上每種大小的瀏覽器。

以下是頁面示例:
[死鏈接已刪除]

#container {
   max-width: 1280px;
   margin: 0 auto;
   padding: 0;
   overflow: hidden;
   font-family: GandhiSansBold;
   position: relative;
}

#artwork {
   /*width: 1065px;*/
   width: 83.203%;
   height: 695px;
   margin: 0;
   float: left;
   overflow: hidden;
   margin-bottom: 10px;
}

請確保,如果瀏覽器尺寸太大,則#artwork高度在任何情況下都不會通過自動調整大小而超過高度:695px。

http://f6design.com/journal/2011/10/18/responsive-elements-that-retain-their-aspect-ratio/

問題歸結為在流暢的設計中保持長寬比。 這條路走得很順利,並且存在許多不錯的解決方案。 我在上面列出了一個。 讓我知道它是否也解決了嵌套div元素的問題。

您需要在調整大小時計算瀏覽器的新高度,然后將新高度設置為圖像:

var TO = false;
var resizeEvent = 'onorientationchange' in window ? 'orientationchange' : 'resize';
$(window).bind(resizeEvent, function() {
  TO && clearTimeout(TO);
  TO = setTimeout(resizeImage, 200);
});
function resizeImage(){
  // browser resized, we count new width/height of browser after resizing
  var height = window.innerHeight || $(window).height();
  // var width = window.innerWidth || $(window).width();
  // you need to change here #artwork height
  var imgHeightInPercent = 30; // browser height is 100%
  var desiredHeight = (height * imgHeightInPercent) / 100;
  // finally we changed #artwork height
  $('#artwork').height(desiredHeight); 
}

最好的方法是使用CSS和百分比值,但是現在我們將使用jQuery。

這是一個使用jQuery並處理resize事件的示例:

(function() {
    var _viewport = $(window),
        _event = 'onorientationchange' in window ? 'orientationchange' : 'resize';

    //add a namespace to event
    _event += ".boxsize";

    //creates the event handler by namespace
    _viewport
        .off(_event)
        .on(_event, fnResizer);

    function fnResizer (e) {
        var gap = 40,
            winWidth = _viewport.width(),
            winHeight = _viewport.height(),
            //add your calculations
            boxWidth = winWidth - gap,
            boxHeight = winHeight - gap;
        //sets the new size of the boxes
        $('#artwork, #container').css({
            "width": boxWidth,
            "height": boxHeight
        });
    }
}());

HTML:

<div id="container">
    <div id="artwork"></div>
</div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM