大家在浏览淘宝,京东等页面时,一定会发现它的轮播部分,把要宣传或者展示的内容用轮播的形式呈现给大家,本节呢,就把代码分享给大家,希望对大家有帮助。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
.contain img {
width: 600px;
height: 350px;
}
.contain {
width: 3000px;
height: 350px;
white-space: nowrap;
font-size: 0;
position: absolute;
}
.wrapper {
width: 600px;
height: 350px;
overflow: hidden;
margin: 0 auto;
position: relative;
}
.spots {
position: absolute;
left: 225px;
bottom: 10px;
}
.spots span {
display: inline-block;
width: 10px;
height: 10px;
border: 3px solid white;
border-radius: 50%;
margin-right: 10px;
}
a {
text-decoration: none;
color: dimgrey;
font-size: 38px;
position: absolute;
top: 130px;
}
a:nth-of-type(1) {
left: 10px;
}
a:nth-of-type(2) {
right: 10px;
}
.effect{
background-color: red;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="contain">
<img src="img/1.jpg">
<img src="img/2.jpg">
<img src="img/3.jpg">
<img src="img/4.jpg">
<img src="img/5.jpg">
</div>
<div class="spots">
<span class="effect"></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
<a href="javascript:void(0);"><</a>
<a href="javascript:void(0);">></a>
</div>
<script type="text/javascript">
var _contain=document.querySelector(".contain") //图片所在区域
var _a1=document.querySelector("a:nth-of-type(1)"); //上一张
var _a2=document.querySelector("a:nth-of-type(2)"); //下一张
var _spots=document.querySelectorAll(".spots span"); //所有小圆点
var _wrapper=document.querySelector(".wrapper"); //最外层区域
var index=0; //控制当前是第几张图片
//下一张切换
function next_pic(){
//到第五张从头开始
if(_contain.offsetLeft<=-2400){
_contain.style.left=0;
}else{
_contain.style.left=(_contain.offsetLeft-600)+"px";
}
index++;
if(index==5){
index=0;
}
spots();
}
//上一张切换
function prev_pic(){
//到第五张从头开始
if(_contain.offsetLeft>=0){
_contain.style.left="-2400px";
}else{
_contain.style.left=(_contain.offsetLeft+600)+"px";
}
index--;
if(index==-1){
index=4;
}
spots();
}
//控制小圆点的背景颜色
function spots(){
for (var i = 0; i < _spots.length; i++) {
if(i==index){
_spots[i].className="effect";
}else{
_spots[i].className="";
}
}
}
//上一张
_a1.onclick=function(){
prev_pic();
}
//下一张
_a2.onclick=function(){
next_pic();
}
//自动轮播
auto();
var id;
function auto(){
id=setInterval("next_pic()",3000);
}
//鼠标悬浮轮播停止
_wrapper.onmouseover=function(){
clearInterval(id);
}
//鼠标离开轮播继续
_wrapper.onmouseout=function(){
auto();
}
</script>
</body>
</html>
其中的图片,大家可以换成自己的图片,代码部分就是做个例子。
有不了解的小伙伴可以在评论留言或者私信小编哦。
本文分享如何利用JavaScript实现轮播图效果,适合在电商等网页中展示内容。代码详细,可替换图片以适应个人需求。对于不熟悉的部分,作者鼓励读者留言提问。

被折叠的 条评论
为什么被折叠?



