jQuery上下滑动切换是一种常见的网页交互效果,通常用于图片轮播、内容切换等场景。通过jQuery的动画效果,可以实现元素向上或向下滑动的动画过渡。
以下是一个简单的jQuery上下滑动切换的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery 上下滑动切换</title>
<style>
.container {
width: 300px;
height: 200px;
overflow: hidden;
position: relative;
}
.item {
width: 100%;
height: 100%;
position: absolute;
display: none;
}
.item.active {
display: block;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="container">
<div class="item active" style="background-color: red;">
Item 1
</div>
<div class="item" style="background-color: green;">
Item 2
</div>
<div class="item" style="background-color: blue;">
Item 3
</div>
</div>
<button id="prev">Previous</button>
<button id="next">Next</button>
<script>
$(document).ready(function() {
var currentIndex = 0;
var items = $('.item');
var totalItems = items.length;
function showItem(index) {
items.removeClass('active').eq(index).addClass('active');
currentIndex = index;
}
$('#prev').click(function() {
var newIndex = (currentIndex - 1 + totalItems) % totalItems;
items.eq(currentIndex).slideUp(500, function() {
showItem(newIndex);
items.eq(newIndex).slideDown(500);
});
});
$('#next').click(function() {
var newIndex = (currentIndex + 1) % totalItems;
items.eq(currentIndex).slideUp(500, function() {
showItem(newIndex);
items.eq(newIndex).slideDown(500);
});
});
});
</script>
</body>
</html>
event.stopPropagation()
防止事件冒泡。通过以上示例代码和解决方法,可以实现一个简单的jQuery上下滑动切换效果,并解决一些常见问题。
领取专属 10元无门槛券
手把手带您无忧上云