效果图:

简单讲讲实现逻辑,先实现简单的布局,带有颜色的滑块通过伪类并定位来实现,同时设置好active的效果,也就是滑块移动到了右边花朵上面。切换效果实现后,就可以通过transition来转换变换属性的一个过渡效果。

本项目使用的jquery,预览时请自行引入jquery。

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .trade_tag {
            display: flex;
            position: relative;
            height: 44px;
            width: 100%;
            border-radius: 4px;
            background-color: #1c1d23;
            cursor: pointer;
        }
        .trade_tag:before {
            content: "";
            position: absolute;
            z-index: 0;
            height: 36px;
            width: calc(50% - 6px);/*考虑到会存在间距的情况下*/
            top: 4px;
            left: 4px;
            background-color: green;
            border-radius: 2px;
            -webkit-transition: background-color 0.2s ease-in-out,-webkit-transform 0.2s ease-in-out;
            transition: background-color 0.2s ease-in-out,-webkit-transform 0.2s ease-in-out;
            transition: background-color 0.2s ease-in-out, transform 0.2s ease-in-out;
            transition: background-color 0.2s ease-in-out, transform 0.2s ease-in-out,-webkit-transform 0.2s ease-in-out;
        }
        .trade_tag.active:before {
            background-color: red;
            -webkit-transform: translateX(calc(100% + 6px));
            transform: translateX(calc(100% + 6px));
        }
        .trade_btn {
            flex:1;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100%;
            font-size: 14px;
            color: #fff;
            z-index: 1;
        }
    </style>
</head>
<body>
    <div class="trade_tag active" style="width:200px;">
        <div class="trade_btn buy">叶子</div>
        <div class="trade_btn sell">花朵</div>
    </div>
</body>
</html>
<script src="./jquery.3.2.1.min.js"></script>
<script>
//点击买入
$(".trade_btn.buy").on('click',function(){
    $('.trade_tag').removeClass('active');
});
//点击卖出
$(".trade_btn.sell").on('click',function(){
    $('.trade_tag').addClass('active');
});
</script>

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐