所以我有一个带有箭头按钮的图片幻灯片,允许用户转到下一张或最后一张图片。如何将这些箭头放在相应侧的图像上或图像中(左侧中间为前一个图像,右侧中间为下一个图像)? 这是我目前的代码:
<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>
答案 0 :(得分:1)
将图像包装在容器中以获得如下的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
,您可以使用absolute
或relative
让他们相对于距离他们最亲近的父级自行定位位置。
这就是我们将.imgContainer
的位置设置为relative
的原因
我们现在可以使用left
,right
,top
和bottom
属性在容器中定位按钮。
查看本文以获得更深入的解释:Absolute Positioning Inside Relative Positioning。
按钮的完美垂直居中更加棘手,需要另外一次黑客攻击所以现在你可以使用bottom: 50%;
,或者在你准备好时潜入Centering in CSS的艺术。