首页 > 解决方案 > Vue.js:在元素处于正确位置之前不显示元素

问题描述

我正在学习 Vue 并且非常喜欢它。我有一个标签,我想在页面加载时将其固定在浏览器窗口的底部。当用户单击选项卡时,它会向上滑动以显示一些内容。

一切都很好。我可以让标签贴在页面底部——点击事件也很好用。

我遇到的问题是我需要计算制表符(和div)的高度才能正确设置 CSS 属性。当页面加载时,您可以看到选项卡向下滑动到位。我想隐藏选项卡,直到所有内容都计算完毕并且位于正确的位置。

这是我正在使用的:

应用程序.js

new Vue({
    el: '#info',
    delimiters: ['${', '}'],
    data: {
        active: false,
        inactive: true,
        styles: {
            'bottom': 0
        },
    },
    methods() {
        toggle: function (event) {
            event.preventDefault();
            this.active = !this.active;
            this.inactive = !this.inactive;
        }
    },
    mounted() {
        let tabHeight = this.$refs.infoTab.clientHeight;
        let boxHeight = this.$refs.infoBox.clientHeight;  // 473px
    
        this.styles.bottom = -boxHeight + 'px';
    }
});

HTML

<div class="info not-active" id="info" @click="toggle" ref="infoTab"
     v-cloak
     v-bind:class="{ active: active }"
     v-bind:style="styles">
     <!-- content -->
</div>

样式.css

[v-cloak] {
    display: none;
}

/* more classes */

.info {
    width: 100%;
    position: fixed;
    &.inactive {
        bottom: -100%;
    }
    &.active {
        bottom: 0 !important;
    }
}

我知道我很接近,我只是不希望用户看到标签滑入到位。它应该就那里。我尝试使用created钩子,但clientHeight不可用。

任何建议都非常感谢!

标签: htmlcssvue.jsuser-interfacecss-transitions

解决方案


我认为你可以只使用 CSS 来解决这个问题,不需要使用任何 Vue 的生命周期钩子,我用 vanilla JS 示例制作了一支笔:

let infoNode = document.getElementById('info');

infoNode.addEventListener('click', () => {
  if (infoNode.style.top) {
    // clear inline top style
    infoNode.style.top = '';
  } else {
    // set top to client height + 2 * border thickness
    infoNode.style.top = `calc(100% - ${infoNode.clientHeight}px - 4px)`;
  }
});
#info {
  font-size: 16px;
  width: 200px;
  border: 2px solid hsl(0, 0%, 80%);
  padding: 8px;
  border-radius: 4px;
  cursor: pointer;
  position: fixed;
  /* 100% height of the viewport subtracting:
  tab height: padding, margin, & font size */
  top: calc(100% - (8px + 8px + 24px));
  /* we center the tab horizontally here using
  50% the width of the viewport - 50% the fixed
  width of the tab */
  left: calc(50% - 200px/2);
  transition: top 0.5s;
}

.title {
  font-size: 24px;
  font-weight: 500;
  margin-bottom: 8px;
  display: block;
}

p {
  margin: 0;
}
<div id="info">
  <span class="title">Click on Me</span>
  <p>
    This is the content of the tab, isn't it great? I think so too, and it can be of any arbitrary length!
  </p>
</div>

基本上,诀窍是使用calcwithtop而不是-100%withbottom进行定位,然后您的选项卡最初会呈现在正确的位置,并且您不必担心当访问者首次加载您的页面时它会不合适。


推荐阅读