使用纯JavaScript时,Bootstrap Carousel记录的事件(slide.bs.carousel)不会触发,而使用JQuery则可以正常工作。
复制步骤:
使用Bootstrap 4.1.1版本(https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/js/bootstrap.min.js)
使用纯JavaScript addEventListener时失败
document.getElementById('carousel').addEventListener('slide.bs.carousel', function () {
console.log('slide fired')
})
工作(使用JQuery绑定)
$('#carousel').on('slide.bs.carousel', function () {
console.log('slide fired')
})
完整代码以重现错误:
<html>
<head>
<title></title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/js/bootstrap.min.js"></script>
</head>
<body>
<div id="carouselExample" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img class="d-block w-100" src="https://cdn1.vectorstock.com/i/1000x1000/27/05/destination-flag-icon-flat-style-vector-19372705.jpg" alt="First slide">
</div>
<div class="carousel-item">
<img class="d-block w-100" src="https://cdn1.vectorstock.com/i/1000x1000/26/80/flag-icon-flat-style-vector-19372680.jpg" alt="Second slide">
</div>
</div>
<a class="carousel-control-prev" href="#carouselExample" 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="#carouselExample" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
<script>
//Does not fire
document.getElementById('carouselExample').addEventListener('slide.bs.carousel', function () {
console.log('slide fired')
})
//Fires
$('#carouselExample').on('slide.bs.carousel', function () {
console.log('slide next clicked')
})
</script>
</body>
</html>