横向 tab 分类切换自动居中效果

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />
<title>横向 tab 分类切换自动居中效果</title>
<style>
.tab {
    width: 100%;
    background: #fff;
    overflow: auto;
}
/* 隐藏滚动条 */
.tab::-webkit-scrollbar {
    display: none;
}
.tab-ul {
    display: flex;
    display: -webkit-flex;
    padding: 0;
}
.tab-ul li {
    height: 30px;
    line-height: 30px;
    flex: 0 0 20%;
    text-align: center;
    list-style: none;
}
.tab-ul li.cur {
    background: pink;
}
</style>
<script src="https://cdn.timecdn.cn/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(function(){
    $('.tab-ul li').on('click', function() {
        $('.tab-ul li').removeClass('cur');
        $(this).addClass('cur');
        var liLeft = $(this).offset().left;
        var liWidth = $(this).width()/2;
        var widths = $(window).width()/2;
        var scrollL = $('.tab').scrollLeft();
        $('.tab').animate({
            scrollLeft: scrollL + (liLeft - widths) + liWidth
        })
    })
});
</script>
</head>
<body>
    <div class="tab">
        <ul class="tab-ul">
            <li class="cur">1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
            <li>5</li>
            <li>6</li>
            <li>7</li>
            <li>8</li>
            <li>9</li>
            <li>10</li>
        </ul>
    </div>
</body>
</html>
Last modification:June 27th, 2020 at 04:15 pm
如果觉得我的文章对你有用,请随意赞赏