加入收藏 | 设为首页 | 会员中心 | 我要投稿 张家口站长网 (https://www.0313zz.com.cn/)- 办公协同、操作系统、混合云网络、数据湖、视觉智能!
当前位置: 首页 > 综合聚焦 > 编程要点 > 语言 > 正文

怎样用jquery实现图片对比的效果?

发布时间:2022-03-12 13:31:42 所属栏目:语言 来源:互联网
导读:这篇文章给大家分享的是有关用jquery实现图片对比的效果的内容,这也是比较常见的效果,小编觉得挺实用的,因此分享给大家做个参考,感兴趣的朋友就跟随小编看看吧。 效果如下 代码部分 !DOCTYPE html html head meta charset=utf-8 title做图片对比/title s
      这篇文章给大家分享的是有关用jquery实现图片对比的效果的内容,这也是比较常见的效果,小编觉得挺实用的,因此分享给大家做个参考,感兴趣的朋友就跟随小编看看吧。
 
     效果如下
 
    代码部分
<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>做图片对比</title>
  <script src="js/jquery-3.4.1.min.js"></script>
  <style>
   *{
    margin: 0px;
    padding: 0px;
    user-select: none;
   }
   .div{
    border: 1px solid lightgray;
    width: 400px;
    height: 200px;
    margin: 10px;
    float: left;
    position: relative;
   }
   .img1{
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    width: 50%;
   }
   .img2{
    position: absolute;
    top: 0;
    bottom: 0;
    left: 50%;
    right: 0;
   }
   .img1,.img2{
    background-position: center center;
    background-size: 400px 200px;
    background-repeat: no-repeat;
   }
   .img1{
    background-position-x: 0;
   }
   .img2{
    background-position-x: 100%;
    filter: invert(100%);
   }
   .bar{
    position: absolute;
    top: 0;
    bottom: 0;
    right:-4px;
    width: 8px;
    background-color: gray;
    cursor: ew-resize;
    opacity: 0.2;
   }
   .stop{
    pointer-events: none;
   }
  </style>
 </head>
 <body>
  <div class="div">
   <div class="img1" style="background-image: url(img/1.jpg);">
    <div class="bar" data-flag="0"></div>
   </div>
   <div class="img2" style="background-image: url(img/1.jpg);"></div>
  </div>
  <div class="div">
   <div class="img1" style="background-image: url(img/2.jpg);">
    <div class="bar" data-flag="0"></div>
   </div>
   <div class="img2" style="background-image: url(img/2.jpg);"></div>
  </div>
 </body>
</html>
<script>
 $(document).ready(function(){
  $(".bar").mousedown(function(){
   $(this).parent().addClass("stop");
   $(this).parent().next().addClass("stop");
   $(this).attr("data-flag","1")
  })
  $(".div").mousemove(function(e){
   var temp = $(this).find('.bar').attr("data-flag");
   if(temp=="1"){
    var w = $(this).width();
    var x = e.offsetX;
    var p = parseFloat((x/w).toFixed(2))*100;
    $(this).children(".img1").css('width',p+'%');
    $(this).children(".img2").css('left',p+'%');
   }
  })
  $(document).mouseup(function(){
   $(".img1,.img2").removeClass("stop");
   $(".bar").attr("data-flag","0")
  })
 })
</script>
    思路解释
    感觉很简单,就是俩图作为背景图片然后控制他的布局位置,控制容器的宽高就行了,需要做适应性优化的还有背景图大小的控制,当然父容器不会变化就不会出问题.

(编辑:张家口站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读