【问题标题】:Manipulate div heights with relation to window height操作与窗口高度相关的 div 高度
【发布时间】:2016-01-01 18:31:49
【问题描述】:

我有几个 div 即

<div class="div_1"></div>
<div class="div_2"></div>
<div class="div_3"></div>

得到窗口高度后

windowHeight = window.innerHeight;

我想将 div 高度操作为窗口高度的比例,例如 div_1 应该是 30%,div_2 应该是窗口高度的 45% 等等。我需要在 javascript/jquery 中执行此操作。

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    你可以简单地使用 CSS

    .div_1 {height:30vh;}
    

    这会将高度设置为视口高度的 30%。 vh 是视口的高度。

    IE > 8 部分支持,Opera 不支持,其他部分完全支持。 http://caniuse.com/#feat=viewport-units

    在 jQuery 中实现

    $('.div_1').css("height", $(document).height()*30/100+"px"); // Will set its height equal to 30% of that of document.
    

    【讨论】:

    • 我需要在 javascript / jquery 中完成
    • @LutaV 检查答案,用 CSS 做有什么问题?
    • 我已经改进了你的答案。检查一下
    【解决方案2】:

    作为替代使用 jquery & data 属性

    <div id="container">
      <div class="div_1" data-percent="30">Div1</div>
      <div class="div_2" data-percent="40">Div2</div>
      <div class="div_3" data-percent="30">Div3</div>
    </div>
    
    <script>
      $(window).resize(function(){
      var height = window.innerHeight;
       console.log('resised',height)
          $('#container>div').each(function(){
             $(this).height(height*parseInt($(this).data('percent'))/100);
            console.log($(this).height(),height*parseInt($(this).data('percent'))/100);
          });
        })
    </script>
    

    【讨论】:

      【解决方案3】:

      我操纵了@void 的答案以获得我期望的答案。代码是

      $('.div_1').height(windowHeight*30/1400+"em");
      

      我将 windowHeight 除以 1400 而不是 100,因为正文字体是 14px,用于将其从 px 更改为 em。

      【讨论】:

        猜你喜欢
        • 2015-02-26
        • 2013-03-06
        • 2017-05-11
        • 1970-01-01
        • 2011-09-09
        • 1970-01-01
        • 2013-04-19
        • 2013-01-02
        • 2019-02-27
        相关资源
        最近更新 更多