[英]Add active class on click for pagination
Within my slideshow, I would like to add and remove an active class to each pagination button on click. 在我的幻灯片中,我想在点击时为每个分页按钮添加和删除活动类。 How can I do this with native JS.
我怎么能用本机JS做到这一点。 My code so far:
我的代码到目前为止:
//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);
}
Try this: 尝试这个:
//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);
}
Explanation: 说明:
We have created variable wich stored ref to active pagination button. 我们创建了变量存储ref到活动分页按钮。 On click we removed class
active
from old active button and change ref to button wich fired click event, then we add class active
to updated active button 点击后,我们从旧的活动按钮中删除了
active
类,并将ref更改为按钮,其中点击了事件,然后我们将类active
添加到更新的活动按钮
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.