在Vue js中设置div的高度

mr.*_*one 4 javascript vue.js

我正在使用 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)`);
           });
Run Code Online (Sandbox Code Playgroud)

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

Tho*_*Brd 7

事实上,computed propertieshttps://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;   
    },
  }
};
Run Code Online (Sandbox Code Playgroud)

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

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

在 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;
}
Run Code Online (Sandbox Code Playgroud)

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


sad*_*ani 5

不确定此更改的上下文,但我会尝试根据有关如何实现此更改的最佳实践为您提供一些解决方案:

  1. 如果父元素具有固定的高度,则子元素height: 100%将采用父元素的高度。

    .parent { 高度:200px; }

    .child { 高度:100%;}

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

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


Nuw*_*tta 2

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

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