关于transition过渡渐变opacity和display一起使用无效的解决方法

2,444 阅读1分钟

先说出我需要做的要求:点击一个按钮后提示框由不显示到显示,然后提示框用3s时间由不透明变成透明

html代码(vue)

<template>
  <button @click="showPrompt">点击后提示框会立即显示然后逐渐变透明</button>

  <div class="prompt" v-show="block" :class="{gradual: change}">我是提示框</div>
</template>

css代码

<style>
  .prompt {
    transition: all 3s linear;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
    background: #ccc;
    opacity: 1;
    border-radius: 4px;
    margin: 20px;
  }
  .gradual {
    opacity: 0;
  }
</style>

js代码

methods: {
    showPrompt() {
      this.block = true;  
      this.change = true;
    }
}

以上代码是不能有效实现需求的,需要稍微修改js代码,以下是正确代码

methids: {
    showPrompt() {
      this.block = true;
      setTimeout(() => {
        this.change = true;
      }, 20);
    },
}

即可以理解成用一个setTimeout延长在渲染display:block后渲染opacity的时间,两者会有冲突

而且需要注意的是:必须是先修改display属性再修改opacity属性才会有效,反过来是无效的

而其中setTimeout时间的值,根据MDC,Firefox中定义的最小时间间隔(DOM_MIN_TIMEOUT_VALUE)是10毫秒,而HTML5定义的最小时间间隔是4毫秒。选一个大于10的数字即可

如有不对的地方或更好的方法请指出,感谢您的阅读