假设我在幻灯片9上,并通过以下链接跳到幻灯片8:
<a class="carousel-control-btn" href="#Carousel"role="button" data-slide-to="8">
我现在在幻灯片8上,是否可以检测到我上一张幻灯片?
我在每张幻灯片上都添加了id
,如下所示:
<div id="slide9" class="carousel-item">
并尝试了此操作,但似乎不起作用:
$('#Carousel').on('slid.bs.carousel',function(f){
if((f.relatedTarget.id == 'slide8') && (f.from.id == 'slide9')) {
console.log("Came from slide 9");
};
});
答案 0 :(得分:0)
您几乎拥有了它。 f.from
不是对象,它是前一个元素的索引。我们可以使用该信息以及f.to
来检索两个元素的id
并进行比较。
$(function() {
$('#carouselExample').carousel();
$('#carouselExample').on('slid.bs.carousel', function(f) {
let fromId = $(this).find('.carousel-item').eq(f.from).attr('id');
let toId = $(this).find('.carousel-item').eq(f.to).attr('id');
if (fromId == "slide1" && toId == "slide2") {
console.log("Came from slide 1");
};
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<div id="carouselExample" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active" id="slide1">
<img class="d-block w-100" src="https://via.placeholder.com/350x150" alt="First slide">
</div>
<div class="carousel-item" id="slide2">
<img class="d-block w-100" src="https://via.placeholder.com/350x150" alt="Second slide">
</div>
<div class="carousel-item">
<img class="d-block w-100" src="https://via.placeholder.com/350x150" alt="Third slide">
</div>
</div>
<a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>