我找到了一个用jQuery制作的图像滑块的教程。我想在纯JS中重新创建相同的功能,但我面临一些问题,将jQuery的animate函数的功能转换为纯JS。
这是代码。 (我面临的问题是不透明度的变化)
HTML :(来自教程)
<!DOCTYPE html>
<html>
<head>
<title>Jquery Slider Demo</title>
<script src="jquery-2.1.3.min.js" type="text/javascript" ></script>
<script type="text/javascript" src="script.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="slides">
<img src="img/1.jpg" />
<img src="img/2.jpg" />
<img src="img/3.jpg" />
<img src="img/4.jpg" />
</div>
</body>
</html>
JS(来自教程):
$(function(){
// initalizing the first image to class 'top'
$('.slides img:first').addClass('top');
//function to alter the image index by changing the class
var change = function (){
var curr = $('.slides img.top');
var next = curr.next();
// if the next image is not available then
// set the class-top to the first image
// then vanish the current image to
// show the previous next image
if(!next.length){
next = $('.slides img:first');
next.addClass('top');
curr.animate({opacity: 0.0},1000, function() {
curr.removeClass('top');
curr.css({opacity: 1.0});
});
}else{
// pick the next image
// set the opacity to 0
// den use animation to make it appear
// above the top image
next.css({opacity: 0.0})
.addClass('top')
.animate({opacity: 1.0}, 1000, function() {
curr.removeClass('top');
});
}
}
// repeat the function execution for every 3 secs
setInterval(change, 3000 );
});
到目前为止我所拥有的:
(function(){
var list = document.getElementsByTagName('img');
for (var i=0; i<list.length; i++ ) {
list[i].addEventListener('transitionend', function(){
this.style.opacity = "1";
this.classList.remove('top');
})
};
list[0].classList.add('top');
var change = function () {
var curr = document.querySelector('img.top');
var next = curr.nextElementSibling;
if(next == undefined) {
next = list[0]
next.classList.add('top');
curr.style.opacity = "0";
}
else {
curr.style.opacity = "0";
console.log('i am working')
next.classList.add('top');
}
}
setInterval(change,3000);
})();
答案 0 :(得分:2)
正如你在下面的评论中提到的那样,没有jQuery的最佳方法是获得一个很好的淡入淡出效果,就是CSS。
function slider(){
var list = document.getElementsByTagName('img');
list[0].classList.add('top');
var change = function () {
console.log('I am working');
var curr = document.querySelector('img.top');
var next = curr.nextElementSibling;
if(next == undefined) {
next = list[0]
}
curr.classList.remove('top');
next.classList.add('top');
}
setInterval(change,3000);
}
.slides img {
/* this is just for the demo slider to run as a slider... */
position:absolute;
top:0;
left:0;
width:100%;
/* This is the CSS for fading */
-webkit-transition: 1s all linear;
opacity: 0;
}
.slides img.top {
opacity: 1;
}
<body onload="slider();">
<div class="slides">
<img src="https://lorempixel.com/400/200/sports/image 1" />
<img src="https://lorempixel.com/400/200/sports/image 2" />
<img src="https://lorempixel.com/400/200/sports/image 3" />
<img src="https://lorempixel.com/400/200/sports/image 4" />
</div>
</body>