javascript - 如何让更改图片的箭头位于图片的两侧?

标签 javascript html css

所以我有一个图片幻灯片,它有箭头按钮,允许用户转到下一张或最后一张图片。如何让这些箭头出现在图片上或图片中适当的一侧(上一张图片的左中和下一张图片的右中)? 这是我当前的代码:

     <head>
  <title>change picture</title>
  <script type = "text/javascript">
      function displayNextImage() {
          x = (x === images.length - 1) ? 0 : x + 1;
          document.getElementById("img").src = images[x];
      }

      function displayPreviousImage() {
          x = (x <= 0) ? images.length - 1 : x - 1;
          document.getElementById("img").src = images[x];
      }

      function startTimer() {
          setInterval(displayNextImage, 6000);
      }
      function startUp(){
      document.getElementById("img").src = images[0];
      }

      var images = [], x = -1;
      images[0] = "image1.jpg";
      images[1] = "image2.jpg";
  </script>
  </head>
  <body onload = "startTimer(); startUp()">
   <button type="button" onclick="displayPreviousImage()"> &laquo</button>
   <img id="img" style="width:500px;height:380px;" src="startpicture.jpg">
  <button type="button" onclick="displayNextImage()"> &raquo</button>
  </div>
  </body>

最佳答案

将您的图像包装在容器中以获得如下 HTML 结构:

<div class="imgContainer">
     <button class="leftButton"></button>
     <img class="slideshowImage">
     <button class="rightButton"></button>
</div>

然后应用像这样的 CSS:

 .imgContainer {
   position: relative;
 }

 .leftButton {
    position: absolute;
    left: 0; bottom: 50%;
 }
  .rightButton {
    position: absolute;
    right: 0; bottom: 50%;
 }

通过指定 position你的按钮的属性是absolute ,你让他们定位自己相对于他们最近的 parent 与 absoluterelative位置。
这就是我们设置 .imgContainer 的原因的位置到relative .
我们现在可以使用 left 在容器中定位按钮。 , right , topbottom属性。

查看这篇文章以获得更深入的解释:Absolute Positioning Inside Relative Positioning .

按钮的完美垂直居中更加棘手并且需要另一个 hack 所以现在你可以只使用 bottom: 50%; ,或深入研究 Centering in CSS 的艺术当您准备好时。

关于javascript - 如何让更改图片的箭头位于图片的两侧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34581451/

相关文章:

javascript - NextJS 无法识别 TypeScript 文件

javascript - 有没有办法在没有 jQuery 的情况下做同样的事情,只使用 CSS3 和 HTML5

javascript - 悬停时更改div颜色

jQuery 检查内联样式

javascript - JQuery,如何组合子选择器?

javascript - 有没有办法在 firebase 中减少请求?

css - 语义正确的 block 引用

html - CSS中图片显示不当

html - 列表溢出到 Div

jquery - 我的 Stack Slider 文本变得模糊,导航也没有循环