0

我正在实现一个Flickity幻灯片,其中包括底部的幻灯片计数器和顶部的幻灯片标题。我已经把它们都放进去了,但是顶部的标题不会显示应该是 img alt 标签的内容。

这就是我所拥有的 - JSfiddle

HTML:

<section class="ux-carousel">
  <div class="carousel">
  <div class="carousel-cell">
  <img class="carousel-cell-image" src="https://source.unsplash.com/5i8l46zW8do" alt="Image 01" width="1170" height="685" />
  </div>
  <div class="carousel-cell">
  <img class="carousel-cell-image" src="https://source.unsplash.com/5i8l46zW8do" alt="Image 01" width="1170" height="685" />
  </div>
  </div>
  <div class="carousel-counter">
  <p class="carousel-status"></p>
  </div>
  <div class="carousel-caption">
  <p class="caption">&nbsp;</p>
  </div>
  </section>

查询:

var flkty = new Flickity('.carousel', {
  imagesLoaded: true,
  percentPosition: false,
  pageDots: false
});
var carouselStatus = document.querySelector('.carousel-status');
var caption = document.querySelector('.caption');

function updateStatus() {
  var slideNumber = flkty.selectedIndex + 1;
  carouselStatus.textContent = slideNumber + '/' + flkty.slides.length;
}
flkty.on( 'select', function() {
  // set image caption using img's alt
  caption.textContent = flkty.selectedElement.alt;
});
updateStatus();

flkty.on( 'select', updateStatus );
4

1 回答 1

4

非常接近,您只是flkty错误地处理了对象;的上下文flkty.selectedElement不是<img>元素,而是整个幻灯片,意思是元素<div class="carousel-cell">

因此,该alt属性不存在,因此无需设置标题。你可以让它更动态地说img在幻灯片标记中定位,按类过滤等,但如果你知道你的幻灯片内容标记结构将保持不变,最简单的解决方案是alt从第一个子元素中获取值滑动。

因此,您的 on select 功能变为:

flkty.on( 'select', function() {
  caption.textContent = flkty.selectedElement.children[0].alt;
});

因为.children返回上下文集中的 HTML 元素数组(例如 的子元素flkty.selectedElement),我们可以使用数组索引表示法来获取第一个元素(例如数组索引 0),在您的标记中是 the <img>,然后alt根据需要访问它.

在这里工作 jsFiddle:https ://jsfiddle.net/b5jr2L0d/3/

于 2018-08-11T19:56:44.427 回答