【问题标题】:Set height of a div in vue js在vue js中设置div的高度
【发布时间】:2018-08-05 06:45:45
【问题描述】:

我正在使用 vue js。我想使用纯 javascript 根据另一个 div 高度设置一个 div。我面临的问题是我无法使用纯 java 脚本设置高度。但我可以使用 jquery 设置它。谁能帮我把这个 jquery 改成 javascript 。给出了我使用的代码

 Vue.nextTick(function () {
            var offsetHeight = document.getElementById('filterSection').offsetHeight;
            $(".searchResultSection").css("max-height",`calc(100% - ${offsetHeight}px)`);
           });

我需要将 jquery 部分更改为 java 脚本。

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    不确定此更改的背景,但我会尝试根据最佳实践为您提供一些解决方案:

    1. 如果父元素的高度是固定的,那么height: 100% 的子元素将采用父元素的高度。

      .父{ 高度:200px; }

      .child { 高度:100%; }

    2. 使用 vue 指令进行 DOM 操作:https://vuejs.org/v2/guide/custom-directive.html

    3. 在要达到高度的元素上使用 v-bind:style="height:calc(100% - ${offsetHeight}px)\"!

    【讨论】:

      【解决方案2】:

      事实上,computed properties (https://vuejs.org/v2/guide/computed.html#Computed-Properties) 是解决您问题的完美选择:

      声明一个计算属性,该属性将返回 filterSectionHeight

      export default {
        name: "App",
      
        computed: {
          filterSectionHeight() {
            const filterSectionDOM = document.getElementById("filterSection");
            return filterSectionDOM ? filterSectionDOM.offsetHeight : 0;   
          },
        }
      };
      

      在您的组件(或 App 组件)中定义您的 div filterSectionsearchResultsSection,不要忘记添加一个 :style 属性来处理动态max-height 提供给模板中的.searchResultsSection

      <div id="filterSection"></div>
      <div class="searchResultsSection"
           :style="{
                  'max-height': `calc(100% - ${filterSectionHeight}px)`
           }">
      </div>
      

      在您的 css 中将每个 div 的高度设置为 100%

      #app {
        height: 600px;
        width: 100%;
      }
      
      #filterSection {
        height: 100%;
        background: rebeccapurple; //https://en.wikipedia.org/wiki/Eric_A._Meyer
      }
      
      .searchResultsSection{
        height: 100%;
        background: rebeccapurple;
        opacity: 0.6;
      }
      

      您将在此处找到完整的演示 > https://codesandbox.io/s/1rkmwo1wq

      【讨论】:

        【解决方案3】:

        您需要使用 javascript DOM 样式来执行此操作。 试试这个。

        Vue.nextTick(function () {
           var offsetHeight = document.getElementById('filterSection').offsetHeight;
           var x = document.getElementsByClassName("searchResultSection");
           x[0].style.maxHeight = "calc(100% - ${offsetHeight}px)";
        });
        

        【讨论】:

        • 我尝试了这个解决方案,但一个错误显示“vue.min.js:6 ReferenceError: calc is not defined”
        猜你喜欢
        • 1970-01-01
        • 2011-01-19
        • 1970-01-01
        • 2021-08-10
        • 1970-01-01
        • 1970-01-01
        • 2011-07-29
        • 1970-01-01
        • 2012-03-24
        相关资源
        最近更新 更多