javascript - 如何在 if 条件下使用“swiper.activeIndex”?
问题描述
我在我的项目中使用 Swiper.js。我想知道当前活动的滑块。
我如何使用swiper.activeIndex
条件if
?
或者,我想为何时达到预期的滑块编写一些代码。
解决方案
嗨,您需要做的是监听您的 swiper 的“slideChange”事件。
要了解有关 swiper 的事件和 api 的更多信息,请查看文档:https ://idangero.us/swiper/api/
下面是一个关于如何做到这一点的简短示例:
<script>
var swiper = new Swiper('.swiper-container');
swiper.on('slideChange', function () {
if(this.activeIndex === 1) {
console.log("IM ON SECOND SLIDE!");
alert("IM ON SECOND SLIDE!");
}
});
</script>
完整的工作示例(代码取自演示页面):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Swiper demo</title>
<!-- Link Swiper's CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.5.0/css/swiper.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.5.0/js/swiper.min.js"></script>
<!-- Demo styles -->
<style>
html, body {
position: relative;
height: 100%;
}
body {
background: #eee;
font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
font-size: 14px;
color:#000;
margin: 0;
padding: 0;
}
.swiper-container {
width: 100%;
height: 100%;
}
.swiper-slide {
text-align: center;
font-size: 18px;
background: #fff;
/* Center slide text vertically */
display: -webkit-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
}
</style>
</head>
<body>
<!-- Swiper -->
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide">Slide 1</div>
<div class="swiper-slide">Slide 2</div>
<div class="swiper-slide">Slide 3</div>
<div class="swiper-slide">Slide 4</div>
<div class="swiper-slide">Slide 5</div>
<div class="swiper-slide">Slide 6</div>
<div class="swiper-slide">Slide 7</div>
<div class="swiper-slide">Slide 8</div>
<div class="swiper-slide">Slide 9</div>
<div class="swiper-slide">Slide 10</div>
</div>
</div>
<!-- Initialize Swiper -->
<script>
var swiper = new Swiper('.swiper-container');
swiper.on('slideChange', function () {
if(this.activeIndex === 1) {
console.log("IM ON SECOND SLIDE!");
alert("IM ON SECOND SLIDE!");
}
});
</script>
</body>
</html>
推荐阅读
- sql - UPDATE..WHERE..EXISTS 的奇怪结果,以 ORA_ROWSCN 作为连接条件
- wordpress - 在 WooCommerce 中登录失败时的警告消息
- python - PathNotFound 错误消息:openFileForRead 必须与文件而不是目录一起使用
- android - 科特林。接口作为参数
- android - Genymotion Translation 已安装,但 apk 仍未安装(该应用程序在 windows 模拟器中运行,因此它可能不是用 amd64 编写的)
- wordpress - Wordpress 如何显示已登录用户已阅读帖子
- microsoft-graph-api - Microsoft Graph API 中的 getSharePointSiteUsageDetail 返回垃圾
- python - 更改熊猫默认“季度”的日期
- android - 如何通过蓝牙/DECT 重新路由 android 音频
- javascript - 用户单击时过滤选择选项下拉列表