我有两个图像滑块,即使我仅单击其中一个上的箭头,它们也会被触发。我只希望函数仅在被单击的滑块上起作用。
我知道我需要使用event.target,这样它才能仅在被单击的箭头上触发。但是,我不确定语法会是什么样,因为我尝试过的所有内容都会给我一个错误。
这是我写的Jquery
//Funtion for gallery slider
$(document).ready(function () {
var arrowRight = document.querySelector('.gallery-arrow-right');
var arrowLeft = document.querySelector('.gallery-arrow-left');
var show = 4;
var width = $('#slider').width() / show;
console.log(width)
var length = $('.slide').length;
$('.slide').width(width);
$('#slide-container').width(width * length)
function sliderNext(e) {
$('.slide:first-child').animate({
marginLeft: -width + -35
}, 'slow', function () {
$(this).appendTo($(this).parent()).css({marginLeft: 0});
});
}
function sliderPrev(e) {
$('.slide:last-child').prependTo($('.slide:last-child').parent()).css({marginLeft:-width});
$('.slide:first-child').animate({
marginLeft: 0
}, 'slow')
}
arrowRight.addEventListener('click', sliderNext )
arrowLeft.addEventListener('click', sliderPrev )
});
这是我的html
<section class="gallery">
<div class="gallery-slider" id="slider">
<h1 class="d-flex justify-content-center">This is the gallery</h1>
<div class="d-flex" style="padding-left: 0; padding-right:0; "id="slide-container" >
<div class="slide">
<a href="#">
<img class="" src="/images/components/gallery_slider/Bathroom_slider.jpg" alt="">
<p class="gallery-slider-title">Shop Bathroom</p>
</a>
</div>
<div class="slide">
<a href="#">
<img class="" src="/images/components/gallery_slider/Dining_slider.jpg" alt="">
<p class="gallery-slider-title">Shop Dining</p>
</a>
</div>
<div class="slide">
<a href="">
<img class="" src="/images/components/gallery_slider/Diningroom_slider.jpg" alt="">
<p class="gallery-slider-title">Shop Dining Room</p>
</a>
</div>
<div class="slide">
<a href="#">
<img class="" src="/images/components/gallery_slider/Kitchen_slider.jpg" alt="">
<p class="gallery-slider-title">Shop Kitchen</p>
</a>
</div>
<div class="slide">
<a href="#">
<img class="" src="/images/components/gallery_slider/Dining_slider.jpg" alt="">
<p class="gallery-slider-title">Shop Slider</p>
</a>
</div>
</div>
</div>
<i class="fa fa-angle-left fa-2x gallery-arrow-left" style="margin-right: 20px;"></i>
<i class="fa fa-angle-right fa-2x gallery-arrow-right"></i>
</section>
箭头是gallery
类容器的子代。因此,根据上下文定位您想要的元素,我建议导航到图库。例如:
$('.slide:first-child')
将更改为:
$(e.target).closest('.gallery').find('.slide:first-child')
然后,您将只定位要单击的图库中的第一张幻灯片。您还必须对:last-child选择器执行相同的操作。