[英]Add active class on click for pagination
在我的幻灯片中,我想在点击时为每个分页按钮添加和删除活动类。 我怎么能用本机JS做到这一点。 我的代码到目前为止:
//Pagination
var p = document.getElementById('pagination');
var phtml = '';
for(var i = 0; i < slides.length; i++) {
phtml+='<button>' + (i+1) + '</button>';
}
p.innerHTML = phtml; // create the pagination buttons
var pbuttons = p.querySelectorAll('button'); // grab all the buttons
for(var i = 0; i < pbuttons.length; i++) {
pbuttons[i].onclick = (function(n) {
pbuttons[i].classList.toggle('active');
return function(){
pauseSlideshow();
goToSlide(n);
};
})(i);
}
尝试这个:
//Pagination
var p = document.getElementById('pagination');
var phtml = '';
for(var i = 0; i < slides.length; i++) {
phtml+='<button>' + (i+1) + '</button>';
}
p.innerHTML = phtml; // create the pagination buttons
var pbuttons = p.querySelectorAll('button'); // grab all the buttons
var activeButton = null; // ref to active button
for(var i = 0; i < pbuttons.length; i++) {
pbuttons[i].onclick = (function(n) {
return function(){
if(activeButton)
// delete class from old active button
activeButton.classList.remove('active');
// change ref, this is current button
activeButton = this;
// add class for new
activeButton.classList.add('active');
pauseSlideshow();
goToSlide(n);
};
})(i);
}
说明:
我们创建了变量存储ref到活动分页按钮。 点击后,我们从旧的活动按钮中删除了active
类,并将ref更改为按钮,其中点击了事件,然后我们将类active
添加到更新的活动按钮
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.