基于jquery的图片轮播 tab切换组件



<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片轮播 Tab 切换组件</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style>
    .slider {
        position: relative;
        width: 600px;
        height: 400px;
        overflow: hidden;
    }
    .slider-images {
        display: flex;
        transition: transform 0.5s ease;
    }
    .slider-image {
        min-width: 100%;
        height: 100%;
        flex-shrink: 0;
    }
    .tabs {
        display: flex;
        justify-content: center;
        margin-top: 10px;
    }
    .tab {
        padding: 10px 20px;
        cursor: pointer;
        border: 1px solid #ccc;
        margin-right: 5px;
        background-color: #f9f9f9;
    }
    .tab.active {
        background-color: #007bff;
        color: white;
    }
</style>
</head>
<body>

<div class="slider">
    <div class="slider-images">
        <img class="slider-image" src="image1.jpg" alt="Image 1">
        <img class="slider-image" src="image2.jpg" alt="Image 2">
        <img class="slider-image" src="image3.jpg" alt="Image 3">
    </div>
</div>

<div class="tabs">
    <div class="tab active" data-index="0">Tab 1</div>
    <div class="tab" data-index="1">Tab 2</div>
    <div class="tab" data-index="2">Tab 3</div>
</div>

<script>
$(document).ready(function() {
    var currentIndex = 0;
    var $sliderImages = $('.slider-images');
    var imageWidth = $('.slider-image').outerWidth(true);

    $('.tab').click(function() {
        var newIndex = $(this).data('index');
        $('.tab').removeClass('active');
        $(this).addClass('active');

        $sliderImages.css('transform', 'translateX(-' + newIndex * imageWidth + 'px)');
        currentIndex = newIndex;
    });

    // 可选:自动轮播
    setInterval(function() {
        currentIndex = (currentIndex + 1) % $('.slider-image').length;
        $('.tabs .tab').eq(currentIndex).click();
    }, 3000); // 每3秒切换一次
});
</script>

</body>
</html>

上述代码实现了一个基于jQuery的图片轮播和Tab切换组件。用户可以通过点击Tab来切换图片,同时组件也支持自动轮播。样式部分可以根据需要进行调整。