javascript - 检查 jQuery slider 的最后一个子项

标签 javascript jquery slider

我正在制作一个 jQuery slider ,基本上,我通过将当前内存类添加到我的 memory2container 的每个子项来显示 slider 所显示的内容。

问题是当我到达最后一个 slider 而不是返回到第一个 slider 并重新开始时,它就会停止工作。

您可以在此处查看我为此使用的简单代码:

$('.amsheart').click(function() {
 var cm = $('.memories2container').children('.currentmemory:first');
 var nm = cm.nextAll('.memory:first');
 if(cm.is('.memories2container:last-child')){
   nm = $('.memories2container').children('.currentmemory:first'); 
   cm.removeClass('currentmemory');
   nm.addClass('currentmemory');
 }
 else{
   cm.removeClass('currentmemory');
   nm.addClass('currentmemory');
 }
 
});
.amsheart{position:relative; transform: rotate(-5deg);}

.amsterdam{position:absolute; left:851px; top:37px;}


.memory{display:none;}

.currentmemory{display:block;}

.fade {
  -webkit-animation-name: fade;
  -webkit-animation-duration: 3s;
  animation-name: fade;
  animation-duration: 3s;
}

@-webkit-keyframes fade {
  from {opacity: .1} 
  to {opacity: 1}
}

@keyframes fade {
  from {opacity: .1} 
  to {opacity: 1}
}

.fadeout{opacity:1.0; transition: opacity 2s;}
.fadeout:hover{opacity:0.0; transition:opacity 2s; }
<div class="memories2container" style="width:550px; height:600px; position:absolute; right:50px; top:100px; transform:rotate(1deg);">
    <div class="memory currentmemory fade" style="width:100%; height:100%; position:absolute; top:0px; left:0px; ">
	  <div class="first fadeout" style="background-image: url('images/20170520_115819.jpg');"><div class="pin1"></div><div class="pin2"></div><div class="pin3"></div><div class="pin4"></div></div>
	  <div class="second" style="background-image: url('images/20170520_115845.jpg');"><div class="pin1"></div><div class="pin2"></div><div class="pin3"></div><div class="pin4"></div></div>
	  <p style="transform:rotate(1deg); position:absolute; top:315px; left:40px; width:500px; height:auto; margin:auto; margin-top:15px; font-family: 'Covered By Your Grace', cursive; font-weight:600; font-size:23px;">37, esta fue nuestra acojedora "casita" durante 3 dias en Amsterdam,  aunque parece pequeñita dentro habia espacio de sobra!</p>
	  <p style="position:absolute; top:415px; left:150px; transform:rotate(1deg); font-size:22px; font-weight:600;">y nuestros vecinos eran adorables XD</p>
	</div>
	<div class="memory fade" style="width:100%; height:100%; position:absolute; top:0px; left:0px; ">
	  <div class="first fadeout" style="background-image: url('images/20170522_124602.jpg');"><div class="pin1"></div><div class="pin2"></div><div class="pin3"></div><div class="pin4"></div></div>
	  <div class="second" style="background-image: url('images/20170522_112958.jpg');"><div class="pin1"></div><div class="pin2"></div><div class="pin3"></div><div class="pin4"></div></div>
	  <p style="transform:rotate(0.5deg); position:absolute; top:305px; left:38px; width:500px; height:auto; margin:auto; margin-top:15px; font-family: 'Covered By Your Grace', cursive; font-weight:600; font-size:23px;">Nuestro último dia en Lucky Lake, un lugar encantador! Mientras tu dabas los ultimos toques a tu perfecto ensayo en español yo me relajaba en la hamaca...</p>
	  <p style="position:absolute; top:435px; left:154px; transform:rotate(-2deg); font-size:22px; font-weight:600;">todos deberian tener derecho a una hamaca!</p>
	</div>
	<div class="memory fade" style="width:100%; height:100%; position:absolute; top:0px; left:0px; ">
	  <div class="first" style="background-image: url('images/20170521_030407.jpg');"><div class="pin1"></div><div class="pin2"></div><div class="pin3"></div><div class="pin4"></div></div>
	  <p style="transform:rotate(0.5deg); position:absolute; top:315px; left:26px; width:500px; height:auto; margin:auto; margin-top:15px; font-family: 'Covered By Your Grace', cursive; font-weight:600; font-size:23px;">Calentando nuestra cena en la calidez de nuestra caravana tras un largo dia visitando la hermosa ciudad...</p>
	  <p style="position:absolute; top:422px; left:140px; transform:rotate(1deg); font-size:22px; font-weight:600;">no es un Subway pero it's okeeyy !</p>
	</div>
	<div class="memory fade" style="width:100%; height:100%; position:absolute; top:0px; left:0px; ">
	  <div class="first fadeout" style="background-image: url('images/20170520_121454.jpg');"><div class="pin1"></div><div class="pin2"></div><div class="pin3"></div><div class="pin4"></div></div>
	  <div class="second" style="background-image: url('images/patitos.gif');"><div class="pin1"></div><div class="pin2"></div><div class="pin3"></div><div class="pin4"></div></div>
	  <p style="transform:rotate(0.5deg); position:absolute; top:315px; left:26px; width:500px; height:auto; margin:auto; margin-top:15px; font-family: 'Covered By Your Grace', cursive; font-weight:600; font-size:23px;">Nuestros vecinos nos acompañan en el desayuno?! son una familia entera de patitos muy monos</p>
	  <p style="position:absolute; top:422px; left:140px; transform:rotate(1deg); font-size:22px; font-weight:600;">ellos son otro tipo de churris con plumas !</p>
	</div>
  </div>
  <div class="amsterdam">
    <span>I</span>
    <img class="amsheart" src="images/heart3.png">
    <span>AMSTERDAM</span>
  </div>

最佳答案

递增索引

"Problem is when I reach the last slider instead of going back to the first slider and starting over it stops working."

您无法继续从最后一个位置移动到第一个位置的原因是因为您需要增量跟踪。使用 .nextAll 并引用 first-childlast-child 而没有真正了解第一个和最后一个之间的确切含义会让你陷入困境因为这些引用是从整个 NodeList 或数组的 Angular 来看的。您需要来自事件元素的索引位置的引用点。如果没有这个,你就没有停止点,如果没有停止点,像 .nextAll()children 这样的方法将继续,最终找不到任何东西,然后失败。

确定应用的哪一部分真正“驱动”整个过程并增加计数。您所需要的只是声明一个值为 0 的变量,然后在每次迭代(循环)或在您的情况下单击按钮时递增它。

   var idx = 0;

   $('button').on('click', function() {
      
      idx++;
      
      ...the rest of the code...

    });

接下来,通过确定正在计数和/或遍历的元素总量来确定循环的限制。 99% 的情况下它是一个集合,特别是数组、NodeList、HTMLCollection 或对象文字(甚至是字符串)。很可能,这可以通过 .length 属性轻松完成。通过实现限制,您将确定周期结束和开始的时间和地点。通过比较当前计数和涉及的元素总数(总数为 -1 来抵消 0 计数)来做到这一点

   var idx = 0;

   $('button').on('click', function() {
      
      idx++;

      if (idx > (array.length -1)) {
        
         idx = 0;
   
       }

       ...the rest of the code...

    });
<小时/>

引用资料位于演示下方

详细信息在演示中评论

演示

// Same as $(document).ready(function() {...
$(function() {

  // Reference main#frame as jQObj
  var frm = $('#frame');
  
  // Declare the base url to the images location
  var base = "https://i.imgur.com/";
  
  /* Declare an array of strings; Each string is an
  || image fileName and extension
  */
  var path = ['6qGdA1e.jpg', 'iBug1U8.jpg', 'EK7A1RX.jpg', 'exivDl4.jpg', 'qQxmYLj.jpg', 'zHvmZz3.jpg', 'rmx1Y0y.jpg', 'XAYwLxo.jpg', 'TQviM2Y.jpg', 'KrKOLmh.jpg'];
  
  //Get a count/Set a count
  var qty = path.length;
  var cnt = 0;

  // Run the array thru `map()` 
  path.map(function(img, idx, path) {
  
    /* This string is written as a Template Literal
    || ${var} is an interpolated variable
    || Refer to posted reference for details
    */
    var img = `<div class='image'><img src='${base}${path[idx]}' style='object-fit:contain' width='100%' height='100%'></div>`;
    
    /* After that, insert img into main#frame
    || Unlike innerHTML, insertAdjacentHTML()
    || does not overwrite old content.
    */
    frm[0].insertAdjacentHTML('beforeend', img);
    return img;
  });
  
  // Set the first image with the .active class
  $('.image').first().addClass('active');

  function movePaths(e) {
  
    // Increment cnt
    cnt++;
    
    // if cnt is more than 6...
    if (cnt > qty - 1) {
    
      // Reset cnt;
      cnt = 0;
    }
    
    // Get all div.image and remove .active class
    $('.image').removeClass('active');
    
    /* Get the div.image at the position 
    || within the $('.image') object that matches
    || the number cnt currently in and add
    || .active class to it
    */
    $('.image').eq(cnt).addClass('active');
  }
  
  /* Delegate the click event to button.heart 
  || callback is movePaths()
  */
  $('.heart').on('click', movePaths);

});
/* Set H/W 100/100% so that the rest of your
|| layout has a reference when using relative 
|| measurements like `%` 
*/
html,
body {
  height: 100%;
  width: 100%;
  font: 400 16px/1.5 "Palatino Linotype"
}
/* In general, a parent element should have 
|| position:relative
|| The children elements should have 
|| position:absolute
*/ 
#frame {
  position: relative;
  background: rgba(0, 0, 0, 0);
  display: flex;
  overflow: hidden;
  width: 96%;
  height: 75vh;
}

/* Using display:table allows the container size to
|| conform to its contents
*/
.image {
  position: absolute;
  width: 100%;
  height: 100%;
  max-height: 0;
  opacity: 0;
  display: table;
}

/* A .class repeat selector is a valid and safe
|| way to boost specificity. For details see references.
*/
.active.active {
  opacity: 1;
  height: 75vh;
  max-height: 600px;
  top: 0;
  bottom: 0;
  z-index: 222;
  animation: IN;
  transition: all 1s ease-in;
}

.heart {
  border: 0 none transparent;
  background: rgba(0, 0, 0, 0);
  outline: 0 none transparent;
  cursor: pointer
}

.heart::after {
  content: '💖';
  font-size: 32px
}

@keyframes IN {
  0 {
    opacity: 0;
    height: 0;
    transform: translateX(0)
  },
  33% {
    opacity: .33;
    height: 33%;
    transform: translateX(9vh)
  },
  66% {
    opacity: .66;
    height: 66%;
    transform: translateX(18vh)
  },
  100% {
    opacity: 1;
    height: 100%;
    transform: translateX(27vh)
  }
}
-
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">
  <title></title>
  <style>

  </style>
</head><!-- This end tag is always before...
...the beginning of the body tag-->
<body>
  <main id='frame'>
  </main>
  <nav class="control">
    <label for='heart'>I</label>
    <button class="heart" type='button'></button>
    <label for='heart'>HAMSTER &#128057; HAM &#128055;</label>
  </nav>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>

</body><!--body end tags are the second to the last
Remember a document can only have one <head> tag and one <body> tag.-->

</html>

引用文献

关于javascript - 检查 jQuery slider 的最后一个子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47491145/

相关文章:

javascript - 如何遍历页面上的所有元素,包括伪元素?

Jquery slider 。以前的职位

javascript - 听取下拉菜单中的值变化?

JavaScript 图像 slider 在图像之间不褪色

javascript - 防止 map 区域点击重新加载页面

javascript - 带有ajax的动态html5音频播放列表

javascript - 如何使用 JSON-LD 标记面包屑列表中的最后一个非链接项

php - 输入类型 ="file"更改后是否可以重新加载表单?

javascript - 如果 contentedittable = false,如何更改内容样式?

jquery - 解除绑定(bind) - 删除 - 终止 jQuery 插件