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

幻灯片容器中右箭头无法适配问题求助

问题:幻灯片右箭头无法放入容器内

我正在制作图片幻灯片,尝试在容器两侧添加左右箭头,但右箭头无法放入container div中。我是编程新手,参考了W3Schools的幻灯片教程,不想完全照搬,接下来打算尝试用JavaScript解决问题。

HTML代码

<html>
  <head>
    <title>Practice</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="style.css">
    <script src="myscript.js"></script>
  </head>

  <body>
    <div class="container">
      <div class="regular-img">
        <img id="city" src="NYC.jpg" />
      </div>

      <div class="regular-img">
        <img id="king" src="KING.jpg" />
      </div>

      <a id="prev">&#10094;</a>
      <a id="fwd">&#10095;</a>
    </div>
  </body>
</html>

CSS代码

* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

.container {
  background-color: yellow;
  height: 65vh;
  width: 95vw;
  margin: 75px auto;
}

img {
  height: 100%;
  width: 100%;
  object-fit: cover;
}

.regular-img {
  display: none;
}

a {
  cursor: pointer;
  /* color: white; */
  /* opacity: 0.7; */
  position: absolute;
  top: 50%;
  font-size: 18px;
  user-select: none;
  font-weight: bold;
  padding: 16px;
  margin-top: -22px;
  width: auto;
}

#fwd {
  right: 0;
}

解决方案

问题根源:绝对定位的箭头默认以整个页面(body)为参照,而非.container,导致右箭头跑到页面最右侧,不在容器内。

修改步骤:

  1. 给.container添加相对定位,让内部绝对定位元素以它为参照:
.container {
  background-color: yellow;
  height: 65vh;
  width: 95vw;
  margin: 75px auto;
  position: relative; /* 添加这一行 */
}
  1. 调整右箭头的right值,让它贴在容器内部右侧(可根据需求调整数值):
#fwd {
  right: 10px; /* 替换原来的right:0 */
}
  1. 可选:给左箭头也设置left值,让它在容器左侧内部:
#prev {
  left: 10px;
}

这样左右箭头就会乖乖待在容器的两侧了,之后你可以继续用JavaScript实现幻灯片的切换逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 04:27:31