用jQuery实现前后对比展示效果

2022-10-22

通过鼠标拖拽,查看前后状态变化,这种组件常见于演示产品如性能、色彩等前后对比情况。



HTML

<div class="ba_slider">
    <div class="handle"></div>
    <div class="up"><i></i></div>
    <div class="down"><i></i></div>
    <em class="label">after</em>
    <em class="label lr">before</em>
</div>


CSS

.ba_slider{width:900px; height:450px; margin:200px auto; position:relative;}
.up{position:absolute; z-index:1; top:0; bottom:0; left:0; width:50%; overflow:hidden;}
.up i {display:block; height:100%; background:url("10.jpg"); background-position:center center; background-repeat:no-repeat; background-size:cover;}
.down{position:absolute; top:0; bottom:0; left:0; right:0;}
.down i {display:block; height:100%; background:url("11.jpg"); background-position:center center; background-repeat:no-repeat; background-size:cover;}
.handle{position:absolute; z-index:2; left:50%; top:50%; transform:translateY(-50%); width:1px; height:100%; background:rgba(255, 255, 255, 1.0); cursor:ew-resize;}
.handle::after {content:"drag"; position:absolute; left:50%; top:50%; transform:translateX(-50%) translateY(-50%); width:60px; height:60px; border-radius:100%; display:flex; justify-content:center; align-items:center; background:#FFFFFF; box-shadow:0 10px 20px rgba(0, 0, 0, .1); transition:all 0.3s ease-out 0s;}
.stop{pointer-events:none;}
.handle.stop::after {width:50px; height:50px;}
.ba_slider .label {display:block; font-style:normal; padding:4px 10px; position:absolute; left:20px; bottom:20px; z-index:2; font-size:12px; background:#FFFFFF;}
.ba_slider .label.lr {left:auto; right:20px;}


JavaScript

$(".up").find('i').css('width',$('.ba_slider').width());
$(".handle").mousedown(function(){
    $(this).parent().find('.up').addClass("stop");
    $(this).attr("status","1");
    $(this).addClass("stop");
})
$(".ba_slider").mousemove(function(e){
    var temp = $(this).find('.handle').attr("status");
    if(temp=="1"){
        var w = $(this).width();
        var x = e.offsetX;
        var p = parseFloat((x/w).toFixed(2))*100;
        $(this).children(".up").css('width',p+'%');
        $(this).children(".handle").css('left',p+'%');
    }
})
$(document).mouseup(function(){
    $(".up").removeClass("stop");
    $(".handle").removeClass("stop");
    $(".handle").attr("status","0")
})