这是我参与8月更文挑战的第3天,活动详情查看:8月更文挑战
既然前端大佬们说,“一个合格的前端至少也要能够达到会写轮播图”,作为前端小白怎么不就动手实现一下呢?
实现思路是仿照着一个大佬的文章做的:产品经理:能不能让这串数字滚动起来?
把你要轮播的图片横着排列,然后绝对定位,再定义一个代表
index的变量,点击箭头改变变量的值,再把变量映射到DOM的style属性上,最后再用overflow: hidden;隐藏掉露在外面的那些图
Talk is Cheap, Show me the Code!
实现过程中有一个缺憾,希望实现大佬文章中的越界阴影效果,但是很遗憾目前还不知道怎么实现。正在求教中~~
实现中注意的点:
-
如何给div绑定click事件:写习惯了vue,一时不知道基础HTML如何写了。onclick绑定函数一定要写小括号,即
onclick="left"是不可以的。 -
三张图片,如何循环播放:将绝对定位的位置值设置为总长度的余数。如代码中为:
a = (a+-300) % max
<!DOCTYPE html>
<body class="center">
<div class="showbox border">
<div class="left border" onclick="left()">
左
</div>
<div class="right border" onclick="right()">
右
</div>
<div id="imgbox" class="center imgbox">
<img class="myimg" src="https://cdn.pixabay.com/photo/2021/07/29/20/23/mountains-6508015_960_720.jpg" />
<img class="myimg" src="https://cdn.pixabay.com/photo/2021/07/29/21/03/cereals-6508088__340.jpg" />
<img class="myimg" src="https://cdn.pixabay.com/photo/2018/01/03/05/33/the-sun-3057622__340.jpg" />
</div>
</div>
</body>
<script>
let a = 0
let max = 300 * 3;
window.onload = function() {
refresh();
}
function refresh() {
document.getElementById("imgbox").style.left = a + "px";
}
function left() {
a = (a-300)%max;
refresh();
}
function right () {
a = (a+300)%max;
refresh();
}
</script>
<style>
body {
width: 100%;
height: 100%;
/* z-index: 1; */
background-color: rgba(0, 0, 0, 0.5);
}
.center {
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
}
.showbox {
width: 300px;
height: 300px;
/* background: chocolate; */
position: relative;
overflow: visible;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
/* z-index: 3; */
opacity: 1;
/* background-color: white; */
}
.left {
position: absolute;
left: 0;
top: 50%;
cursor: pointer;
background: blue;
z-index: 4;
}
.right {
position: absolute;
right: 0;
top: 50%;
cursor: pointer;
background: blue;
z-index: 4;
}
.border {
border: 1px solid black;
}
.centerimg {
width: 100%;
height: 100%;
}
.myimg {
width: 300px;
height: 300px;
z-index: 2;
opacity: 1;
/* filter: alpha(opacity=60); */
}
.imgbox {
position: absolute;
left: -300px;
top: 0;
}
</style>
</html>
欢迎指正!