所以我有一个图片幻灯片,它有箭头按钮,允许用户转到下一张或最后一张图片。如何让这些箭头出现在图片上或图片中适当的一侧(上一张图片的左中和下一张图片的右中)? 这是我当前的代码:
<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()"> «</button>
<img id="img" style="width:500px;height:380px;" src="startpicture.jpg">
<button type="button" onclick="displayNextImage()"> »</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 与 absolute
或 relative
位置。
这就是我们设置 .imgContainer
的原因的位置到relative
.
我们现在可以使用 left
在容器中定位按钮。 , right
, top
和 bottom
属性。
查看这篇文章以获得更深入的解释:Absolute Positioning Inside Relative Positioning .
按钮的完美垂直居中更加棘手并且需要另一个 hack 所以现在你可以只使用 bottom: 50%;
,或深入研究 Centering in CSS 的艺术当您准备好时。
关于javascript - 如何让更改图片的箭头位于图片的两侧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34581451/