繁体   English   中英

水平滑块错误 - 多个水平滑块与本机 JavaScript 具有相同的类,所有滑块一起工作我如何解决它

[英]horizontal slider bug - more than one horizontal slider with same classes with native JavaScript , All slider working together how I can solve it

#horizo​​ntal 滑块错误 - 多个水平滑块与本机 JavaScript 具有相同的类,所有滑块协同工作如何解决它###第一个水平滑块## '''
/* 声明变量 */

    let moveRight = document.querySelectorAll('.move-right');
    let moveLeft = document.querySelectorAll('.move-left');
    let left = document.querySelector('.move-left');
    let right = document.querySelector('.move-right');
    const slides = document.querySelectorAll('.slide');
    let x = 0;

    /* Function to slide Sliders Divs To left when click on arrow with class = ".move- 
  left"*/
    for(let i = 0; i < moveLeft.length; i++){
     moveLeft.forEach(function(left){
        left.addEventListener('click', function(){

        x++;
        for (let i = 0; i < slides.length; i++){
            if(x==0) {slides[i].style.left = "0px";}
            if(x==1) {slides[i].style.left = "-320px";}
            if(x==2) {slides[i].style.left = "-640px";}
            if(x==3) {slides[i].style.left = "-960px";}
            if(x==4) {slides[i].style.left = "-1280px";}
            if(x==5) {slides[i].style.left = "-1600px";}

            if(x>5) {x=5;}
        }
      })});
    }
   /* Function to slide Sliders Divs To Right  when click on arrow with class = ".move- 
  right"*/

    for(let i = 0; i < moveRight.length; i++){
      moveRight.forEach(function(right){
        right.addEventListener('click', function(){

        x--;
        for (let i = 0; i < slides.length; i++){
            if(x==0) {slides[i].style.left = "0px";}
            if(x==1) {slides[i].style.left = "-320px";}
            if(x==2) {slides[i].style.left = "-640px";}
            if(x==3) {slides[i].style.left = "-960px";}
            if(x==4) {slides[i].style.left = "-1280px";}

       if(x < 0) {x=0;}

  }
 })});
}

'''

您尚未添加 HTML 代码,但我假设您有一个部分或 div 标签,其中包含幻灯片和左/右按钮。 您可以稍微修改您的代码,以便您仅在容器中定位幻灯片。 这样,即使您有多个滑块,也只有您单击的按钮的那个滑块才会起作用。

left.addEventListener('click', function(event){
    // Assuming the parent div has a class of container
    const container = event.target.closest('.container');
    // Selecting only those slides that are a part of the container where the button has been clicked
    const slides = container.querySelectorAll('.slides');
    // Rest of your logic goes here
});

HTML将是这样的

<div class='container'>
    <div class='slide'>Content here</div>
    <button class='move-left'>Left</button>
    <button class='move-right'>Right</button>
</div>

注意: closest()在 IE 中不起作用,如果你想支持 IE,你可能需要为它添加一个 polyfill。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM