【发布时间】:2017-11-29 11:36:22
【问题描述】:
我创建了一个带有自定义滑块导航的滑块。代码如下:
<!-- Slider Parent -->
<div class="col-md-6 col-xs-12">
<div class="gallery slider-parent">
<% @activity.galleries.each_with_index do |gallery, index| %>
<%= image_tag gallery.documentation.url(:large, width: '100%') %>
<% end %>
</div>
</div>
<!-- Slider Navigation -->
<div class="col-md-6 col-xs-12">
<div class="slider-nav">
<% @activity.galleries.each_slice(3) do |galleries| %>
<div class="row">
<% galleries.each do |gallery| %>
<div class="col-md-4">
<a href="#"><%= image_tag gallery.documentation.url(:medium) %></a>
</div>
<% end %>
</div>
<% end %>
</div>
</div>
这里的 JS 看起来像 application.js:
// Image gallery
$('.gallery').slick( {
autoplay: true,
arrows: false
});
var $parent = $(".gallery.slider-parent");
var $nav = $(".slider-nav").find("a");
$nav.click(function(e){
e.preventDefault();
slideIndex = $(this).index();
$parent.slick('slickGoTo', parseInt(slideIndex) );
});
但是 Slider Parent 与我单击的 Slider Navigation 不匹配。我认为问题在于$nav = $(".slider-nav").find("a"); 不会同步滑块父级。我尝试将滑块导航代码更改为如下所示:
<!-- Slider Navigation -->
<div class="col-md-6 col-xs-12">
<div class="slider-nav">
<% @activity.galleries.each do |gallery| %>
<a href="#"><%= image_tag gallery.documentation.url(:medium) %></a>
<% end %>
</div>
</div>
而且它有效。但是,滑块导航没有我想要的样式。有什么建议吗?
更新
我尝试使用 jQuery 查找关键字来定位最深的元素,结果发现:
// Select deepest child elements
(function( $ ) {
$.fn.deepest = function(selector){
var targ = $(this);
var result = [];
//If there is no selector just drill down to the furthest child
if (typeof (selector) === 'undefined') {
selector = "*";
while ( $(targ).children(selector).length ) {
targ = $(targ).children(selector);
}
return targ;
};
//Get to the deepest point from which the selector can be seen
while ( $(targ).find(selector).length ) {
targ = $(targ).children('*');
}
//Only keep the elements that match the selector
targ = $(targ).each(function(i, obj){
if ($(obj).is(selector) ) {
result.push(obj)
}
});
return $(result);
};
})( jQuery );
// Image gallery
$('.gallery').slick( {
autoplay: true,
arrows: false
});
var $parent = $(".gallery.slider-parent");
var $nav = $(".slider-nav").deepest('a');
$nav.click(function(e){
e.preventDefault();
slideIndex = $(this).index();
$parent.slick('slickGoTo', parseInt(slideIndex) );
});
我使用控制台检查$(".slider-nav").deepest('a');,它的位置很好,但滑块导航仍然不起作用。
更新 #2
我尝试了 Christos Lytras 的方法来调试并找出哪个不起作用。
我运行 jQuery(".gallery.slider-parent").slick('slickGoTo', 2); 并且它有效。
然后我修改了代码,添加了这个代码console.log("Slide index:", slideIndex, parseInt(slideIndex));。每当我单击导航中的任何图像(幻灯片索引,2,3 或 4)时,它总是打印幻灯片索引:0 0。
所以,问题就在那里,但是我该如何解决呢?似乎 javascript $nav 没有在点击时运行,因为 $nav 上的所有滑块索引都设置为 0,因为它位于不同的列和行中。有什么解决办法吗?
【问题讨论】:
标签: javascript jquery html css ruby-on-rails