You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么我的CSS规则未生效,点击按钮无法实现卡片翻转效果?

问题原因

你的代码存在3处核心逻辑错误,修正后即可正常实现翻转效果:

  • 翻转触发对象绑定错误:flipped类应该控制整个内部卡片容器flip-card-inner的旋转,而非单独绑定在正反两个卡片面上
  • 初始样式错误:flip-card-inner默认额外加了transform: rotateY(180deg)属性,导致初始状态就是翻转后的
  • 交互逻辑错误:点击按钮仅将isFlipped设为true,无法实现正反状态切换

修正后代码

HTML

<div id="myApp">
  <div class="flip-card">
    <!-- 把flipped类绑定到内部容器上 -->
    <div class="flip-card-inner" :class="{ flipped: isFlipped }">
      <div class="flip-card-front">Side A</div>
      <div class="flip-card-back">Side B</div>
    </div>
  </div>
  <button @click="onButtonClick">Flip</button>
</div>

CSS

.flip-card {
  background-color: transparent;
  width: 300px;
  height: 300px;
  perspective: 1000px;
}

.flip-card-inner {
  position: relative;
  width: 100%;
  height: 100%;
  text-align: center;
  /* 删掉默认的rotateY(180deg),初始保持0度正面朝上 */
  transition: transform 0.6s;
  transform-style: preserve-3d;
  box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
}

/* 翻转状态下整个内部容器转180度 */
.flipped {
  transform: rotateY(180deg);
}

.flip-card-front, .flip-card-back {
  position: absolute;
  width: 100%;
  height: 100%;
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
}

.flip-card-front {
  background-color: #bbb;
  color: black;
}

.flip-card-back {
  background-color: #2980b9;
  color: white;
  transform: rotateY(180deg);
}

JavaScript

const MyApp = {
  data() {
    return {
      isFlipped: false
    }
  },
  methods: {
    onButtonClick() {
      // 切换翻转状态,支持来回翻转
      this.isFlipped = !this.isFlipped;
    }
  }
}

Vue.createApp(MyApp).mount('#myApp');

内容的提问来源于stack exchange,提问作者Dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 04:15:04