javascript - 如何在 CSS 轮播中添加“下一张幻灯片”按钮,同时保持原生滚动?
问题描述
我制作了一个简单的水平轮播,并想添加一个按钮来“跳转到”每个图像/卡片。我很接近一些jquery。
HTML:
<div class="wrap">
<div class="p p1 active"></div>
<div class="p p2"></div>
<div class="p p3"></div>
</div>
<button class="next">NEXT</button>
CSS:
.wrap {
display: flex;
flex-wrap: nowrap;
overflow-x: auto;
position: relative;
width: 100%;
}
.p {
flex: 0 0 auto;
width: 100%;
height: 80px;
}
查询:
$(".next").click(function() {
var $target = $('.p.active').next('.p');
if ($target.length == 0)
$target = $('.p:first');
$('.wrap').animate({
scrollLeft: $target.offset().left
}, 'slow');
$('.active').removeClass('active');
$target.addClass('active');
});
https://codepen.io/drewbots/pen/eYJzQQX
为了简单起见,我更喜欢 vanilla Javascript,但工作 jquery 会很好。在此先感谢您的帮助!
解决方案
使用 offset 方法获取元素相对于文档的位置并滚动到元素使用 animate 与 scrollLeft 和 scrollTop
$(".next").click(function() {
let offset
let active = $('.active')
let target = active.next()
if(active.next()[0] == undefined)
target = $('.p').first()
offset = target.offset()
$('.wrap').animate({
scrollLeft: $('.wrap').scrollLeft() + offset.left,
scrollTop: $('.wrap').scrollTop() + offset.top
})
target.addClass('active')
active.removeClass('active')
})
body {
margin:0;
}
.wrap {
display: flex;
flex-wrap: nowrap;
overflow-x: auto;
position: relative;
width: 100%;
}
.p {
flex: 0 0 auto;
width: 100%;
height: 80px;
}
.p1 {
background-color: #2196F3;
}
.p2 {
background-color: #E91E63;
}
.p3 {
background-color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrap">
<div class="p p1 active"></div>
<div class="p p2"></div>
<div class="p p3"></div>
</div>
<button class="next">NEXT</button>
推荐阅读
- haskell - 当 ghc 抱怨它不在范围内时,如何在 Haskell 中使用实例函数,尽管有导入?
- bash - 优化 grep -f 管道命令
- android - 找不到参数的方法 kapt()
- c++ - 在一个真实的例子中如何从 CRTP 中受益?
- r - “plot.window(...) 中的错误:在 R 中创建交互图时需要有限的 'ylim' 值”错误
- docker - Nginx 简单代理在 Docker 中不起作用
- azure - 指向一个 Blob 容器的多个 Azure 函数应用程序(触发器)
- php - 方法 Illuminate\Routing\Redirector::round 不存在
- php - 为什么 PHP rename($file) 仍在删除文件?
- xaml - XAML:图像未正确居中