提问者:小点点

轮播引导程序5:JQuery到Javascript


我需要一个bootstrap 5轮播,显示多个项目和滑动一次(纯javascript)。

我发现这个codeply解决方案完成了这项工作,它是轻巧、易懂、简短的css和Jquery代码。所以这正是我所需要的,只是它有Jquery depencendy。

我所需要的只是将Jquery代码转换为纯JavaScript。

到目前为止,由于我缺乏知识,唯一的解决办法是在我的身边,它不崩溃,直到这里。一旦代码完全转换为Javascript,它就应该可以工作,就像它可以使用jQuery一样。

jQuery

$('.carousel .carousel-item').each(function() {
    var minPerSlide = 4;
    var next = $(this).next();
    if (!next.length) {  next = $(this).siblings(':first');  }
    next.children(':first-child').clone().appendTo($(this));
    for (var i = 0; i < minPerSlide; i++) {
        next = next.next();
        if (!next.length) { next = $(this).siblings(':first'); }
        next.children(':first-child').clone().appendTo($(this));
    }
});

JavaScript

document.querySelectorAll('.carousel .carousel-item').forEach(function (item) {
    alert('Hello world');
    //var content = item.innerHTML;
    //item.innerHTML=html;
});

编辑:(重要)

我只需要翻译使用$(this)的部分,即Jquery部分...例如:$(this).next();我需要纯javascript的相同行,


共1个答案

匿名用户

试试我对你发布的代码的分叉

https://www.codePley.com/p/tn7rystiwu

const indexInParent node => {
  const children = node.parentNode.childNodes;
  let num = 0;
  for (let i = 0; i < children.length; i++) {
    if (children[i] == node) return num;
    if (children[i].nodeType == 1) num++;
  }
  return -1;
}

document.getElementById('carouselExample').addEventListener('slide.bs.carousel', function(e) {

  /*

  CC 2.0 License Iatek LLC 2018
  Attribution required
    
  */

  var $e = e.relatedTarget;

  const idx = indexInParent($e)
  console.log("IDX :  " + idx);

  const itemsPerSlide = 8;
  const allItems = document.querySelectorAll('.carousel-item')
  const totalItems = allItems.length;
  const parentContainer = document.querySelector('.carousel-inner');


  if (idx >= totalItems - (itemsPerSlide - 1)) {
    const it = itemsPerSlide - (totalItems - idx);
    for (let i = 0; i < it; i++) {
      // append slides to end
      if (e.direction == "left") {
        parentContainer.appendChild(allItems[i])
      } else {
        parentContainer.appendChild(allItems[0]);
      }
    }
  }
});