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

如何在移动图像到达屏幕特定位置时实现水平翻转

实现马里奥碰到边界水平翻转的解决方案

嘿,恭喜你已经成功让马里奥来回移动啦!要实现他碰到容器两端时水平翻转的效果,我们只需要在现有代码基础上,用CSS的transform: scaleX()属性配合你的移动逻辑就可以搞定,很简单的!

核心思路

当马里奥向右移动时(change = 10),保持正常朝向;当他向左移动时(change = -10),通过transform: scaleX(-1)让他水平翻转,这样看起来就像是转身往回走了。我们只需要在切换移动方向的同时,更新这个样式就行。

修改后的完整代码

HTML 代码

<h1>Layers and animation</h1>
<img src="https://i.imgur.com/kDDFvUp.png" class="rotate" width="100" height="100" />
<img src="https://i.imgur.com/kDDFvUp.png" class="rotate" width="100" height="100" />
<img src="https://i.imgur.com/kDDFvUp.png" class="rotate" width="100" height="100" />
<img src="https://i.imgur.com/kDDFvUp.png" class="rotate" width="100" height="100" />
<img src="https://i.imgur.com/kDDFvUp.png" class="rotate" width="100" height="100" />
<img src="https://i.imgur.com/kDDFvUp.png" class="rotate" width="100" height="100" />
<img src="https://i.imgur.com/kDDFvUp.png" class="rotate" width="100" height="100" />
<img src="https://i.imgur.com/kDDFvUp.png" class="rotate" width="100" height="100" />
<img src="https://i.imgur.com/kDDFvUp.png" class="rotate" width="100" height="100" />
<img src="https://i.imgur.com/kDDFvUp.png" class="rotate" width="100" height="100" />
<img src="https://i.imgur.com/kDDFvUp.png" class="rotate" width="100" height="100" />
<div id="container">
  <div id="object"></div>
</div>
<div id="grass"></div>
<br/>
<button onclick="setInterval(moveBlock, 25)">Click Me</button>

CSS 代码

.rotate {
  animation: rotation 8s infinite linear;
}
@keyframes rotation {
  from { transform: rotate(0deg); }
  to { transform: rotate(359deg); }
}
#grass {
  width: 1100px;
  height: 100px;
  margin-top: 0px;
  position: relative;
  background-color: green;
}
#container {
  width: 1100px;
  height: 320px;
  margin-top: 0px;
  position: relative;
  background-color: white;
}
#object {
  width: 251px;
  height: 320px;
  margin-top: 0px;
  position: absolute;
  background-image: url("https://i.sstatic.net/e7Hib.png");
  /* 初始状态保持正常朝向 */
  transform: scaleX(1);
}

JavaScript 代码

var objX = 0;
var change = 10;
function moveBlock() {
  var obj = document.getElementById("object");
  if ((objX + 251) > 1100) {
    change = -10;
    // 向左移动时,水平翻转元素
    obj.style.transform = "scaleX(-1)";
  } else if (objX == 0) {
    change = 10;
    // 向右移动时,恢复正常朝向
    obj.style.transform = "scaleX(1)";
  }
  objX = objX + change;
  obj.style.left = objX + "px";
}

关键修改点说明

  1. 在CSS的#object里添加了初始的transform: scaleX(1),确保马里奥一开始是正常朝向的。
  2. 在JavaScript的方向切换逻辑中,当切换为向左移动(change = -10)时,设置obj.style.transform = "scaleX(-1)";切换为向右移动时,恢复为scaleX(1)。
  3. scaleX(-1)是CSS中实现水平翻转最简便的方式,它只会沿垂直轴翻转元素,不会改变元素的位置、大小或其他样式,完美契合转身的需求。

现在点击按钮,马里奥就会在碰到容器两端时自动转身啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 04:19:10