html文件:
<!doctype html>
<html>
<head>
<meta charset = "utf-8">
<title>Image Slider</title>
<link href = "slider.css" rel = "stylesheet" type = "text/css"> //link to css file
<script src = "slider.js"></script> //link to js file
</head>
<body onLoad = "photoA()"> //change to addEventListener
<div id = "slider">
<img src = "Images/img1.jpg" id = "image" >
<div class = "left_hold"><img onClick = "photo(-1)" class = "left" src = "Images/arrow_left.png"></div> //change to addEventListener
<div class = "right_hold"><img onClick = "photo(1)" class = "right" src = "Images/arrow_right.png"></div> //change to addEventListener
</div>
</body>
</html>
css文件: //造型网
*{
margin:0px;
}
#slider {
height:400px;
width:650px;
margin: 50px auto;
position:relative;
border-radius:4px;
overflow:hidden;
}
#image {
height:400px;
width:650px;
position:absolute;
}
.left_hold {
height: 400px;
width: 100px;
position: absolute;
top: 0px;
left: 0px;
}
.right_hold {
height: 400px;
width: 100px;
position: absolute;
top: 0px;
right: 0px;
}
.left {
height:50px;
width:50px;
position:absolute;
top:40%;
left:20px;
opacity:0;
transition: all .2s ease-in-out 0s;
}
.right {
height:50px;
width:50px;
position:absolute;
top:40%;
right:20px;
opacity:0;
transition: all .5s ease-in-out 0s;
}
.left_hold:hover .left {
opacity:0.6;
}
.right_hold:hover .right {
opacity:0.6;
}
.left:hover .left1
javascript文件:
var imageCount = 1;
var total = 6;
function photo(x) {
var image = document.getElementById('image');
imageCount = imageCount + x;
if(imageCount > total){imageCount = 1;}
if(imageCount < 1){imageCount = total;}
image.src = "Images/img"+ imageCount +".jpg";
clearInterval(time);
time = window.setInterval(function photoA() {
var image = document.getElementById('image');
imageCount = imageCount + 1; //adding image
if(imageCount > total){imageCount = 1;}
if(imageCount < 1){imageCount = total;}
image.src = "Images/img"+ imageCount +".jpg";
},2000); //time interval
}
var time = window.setInterval(function photoA() {
var image = document.getElementById('image');
imageCount = imageCount + 1;
if(imageCount > total){imageCount = 1;}
if(imageCount < 1){imageCount = total;}
image.src = "Images/img"+ imageCount +".jpg";
},2000);
任何人都可以向我解释如何将onLoad和onClick更改为addEventListener? 我是否需要再次更改所有代码? 或者有没有更简单的方法可以在不使用jquery的情况下进行图像滑块?
答案 0 :(得分:1)
left= document.getElementsByTagName('img');
left.addEventListener("click", function(){
//do some things
});
right= document.getElementsByTagName('img');
left.addEventListener("load", function(){
//do some things
});
使用此演示
答案 1 :(得分:1)
window.addEventListener('load', function () {
photoA();
document.getElementById('slider').addEventListener('click', function (e) {
var target = e.target;
if (target.tagName != 'IMG') return;
var classList = target.classList,
hasLeftClass = classList.contains('left'),
hasRightClass = classList.contains('right');
if (hasLeftClass || hasRightClass) photo(hasLeftClass? -1 : 1);
});
});