javascript - How to change status when clicking on a specific node
问题描述
I'm trying to create a gallery. Most of it already works thanks to some online tutorials. On the final page there should be a slider and also some thumbnails to click on which will effect the slider. I tried to achieve this by working with status. The problem I'm facing right now is to change the status when clicking on the matching img.
const imgs = document.querySelectorAll('.imgs img');
let status = 0;
var num = document.querySelectorAll('.profile_pics img').length;
let maxstatus = status + num;
imgs.forEach(img => img.addEventListener('click', imgClick));
function imgClick(){
for(let f = 0; f < imgs.length; f++){
if(imgs[f].click == true){
status = [f];
}
}
}
// Rest of the code (is working)
function reset(){
for(let i = 0; i < maxstatus; i++){
slides[i].style.display = 'none';
slides[i].style.opacity = 0;
slides[i].classList.add('fade_in');
imgs[i].style.opacity = 1;
}
}
function focus(){
imgs[status].style.opacity = opacity;
}
function startSlide(){
reset();
slides[0].style.display = 'block';
}
function slideLeft(){
reset();
slides[status - 1].style.display = 'block';
status--;
focus()
console.log(status);
}
function slideRight(){
reset();
slides[status + 1].style.display = 'block';
status++;
focus()
console.log(status);
}
prevBtn.addEventListener('click', function(){
if(status === 0){
status = maxstatus;
}
slideLeft();
});
nextBtn.addEventListener('click', function(){
if(status === maxstatus - 1){
status = -1;
}
slideRight();
});
startSlide();
I've tried now for a couple of hours but can't find a solution. Worked with console.log of course but simply can't get the status update working when clicking of one of those images.
Help would be appreciated - Thanks a lot
解决方案
完整代码可以在这里找到:粘贴 Bin 链接
更新:
// Global Variable
let status = -1;
let imgs = [
$('#img0'),
$('#img1'),
$('#img2'),
$('#img3'),
$('#img4'),
$('#img5'),
]
// Functions
function imgClick(elm){
status = imgs.indexOf(elm); // This will set the status variable to the element index, using indexOf function. it will check inside of imgs variable which element index it is, if it cant be found status will return a -1 value
}
// Execute
imgs.forEach(img => img.on('click', () => {
imgClick(img);
}));
推荐阅读
- javascript - 在同一域请求中获取 JavaScript 错误“Access-Control-Allow-Origin”
- python - ipython 内核在我的 Windows 10 笔记本电脑上新安装的 anaconda3 的 spyder 中不起作用。它显示错误
- jquery - 如何将 .css() 方法与数组一起使用?
- typescript - 获取 keyof 类吸气剂或获取非吸气剂?
- gradle - 为什么依赖项在 gradle 中排除无效
- selenium - 我有一个用例,我需要在测试结束后保持量角器会话以及浏览器实例处于活动状态。有没有办法这样做?
- javascript - 避免浏览器中出现空的本地存储条目
- python - isinstance() 和 np.issubdtype() 有什么区别?
- r - 为什么在 R 中使用 inside 函数后会创建重复的列?
- python - 如何在网页抓取期间获取 P 标签内的特定数据?