【发布时间】:2019-09-18 19:50:13
【问题描述】:
我有两个图像滑块,即使我只单击其中一个上的箭头,它们也会被触发。我只想让功能只在被点击的滑块上工作。
我知道我需要使用 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>
【问题讨论】:
标签: javascript jquery events target