jquery左右拖拽对比前后效果图片的代码
新旧两张图片效果的不同对比,实现效果通过拖拽按钮对比相同位置的差异。
HTML代码:
<div class="compare"> <div class="pic before" style="background-image:url(before.jpg);"></div> <div class="pic after" style="background-image:url(after.jpg);"></div> <div class="drag"> <div class="button"></div> </div> </div>
CSS代码:
.compare {border:2px solid #888; background-color: #fff; position: relative;} .compare:before {display: block; content: '';padding-bottom:40.625%; } .compare .pic {background:#fff no-repeat center center; background-size: auto 100%; position: absolute; left:0; top:0;width: 100%; height: 100%;} .compare .before {width: 50%; z-index: 2; background-color:#eee;} .compare .drag {height: 100%; top:0; left:50%; width: 5%; z-index: 3; transform: translateX(-50%); position: absolute; display: flex; align-items: center; justify-content: center;} .compare .drag:before {width: 3px; height: 100%; position: absolute; left:50%; top:0; transform: translateX(-50%); background-color: #888; display: block; content: '';} .compare .button {width:100%; padding-bottom: 100%; border-radius: 50%; background: #888 url(../images/drag_arrow.svg) no-repeat center center; background-size: 62.5% auto; cursor: pointer;}
jquery代码:
var _compare = $('.compare'); var _this; _compare.find('.button').mousedown(function(e){ var _downX = e.pageX; _this = $(this).parents('.compare'); var _before = _this.find('.before').width(); var _after = _this.find('.after').width(); var _drag = _this.find('.drag').position().left; _this.mousemove(function(e){ var _moveX = e.pageX; var _diffX = _downX - _moveX; if(Math.floor(_before - _diffX) > 0 && Math.floor(_before - _diffX) < _after) { _this.find('.before').width(Math.floor(_before - _diffX)); _this.find('.drag').css('left', Math.floor(_before - _diffX)); } }); }).mouseup(function(){ _this.off('mousemove'); }); _compare.mouseleave(function(){ _this.off('mousemove'); });
代码思路:
点击指定元素获取鼠标横坐标位置,移动鼠标获取鼠标移动到的横坐标位置,两个横坐标的差值就是鼠标的移动多少的数值,再用元素原来的宽度减去这个数值。