【问题标题】:Comparison Function: How can I hide the text when user slide to left or right of the comparison slider比较功能:当用户向比较滑块的左侧或右侧滑动时如何隐藏文本
【发布时间】:2019-06-13 16:17:40
【问题描述】:

我有这个比较功能,允许用户左右滑动查看前后图像。

一切正常(从 codepen 获得代码)。

虽然有一个问题,我想在图像的左侧和右侧有一个文本(没问题),当用户向左滑动时,我希望左侧文本(当前显示为“文本左侧”)消失当滑块接近“Text Left”块时,当滑块远离“Text Left”块时再次出现,“Text Right”块的功能也相同。

有人知道我该怎么做吗?你可以在这里查看代码。 https://codepen.io/drstrangelovesg/pen/Kjpevp

提前谢谢你们。

$(document).ready(function () {
    $('.ba-slider').each(function () {
        var cur = $(this);
        // Adjust the slider
        var width = cur.width() + 'px';
        cur.find('.resize img').css('width', width);
        // Bind dragging events
        drags(cur.find('.handle'), cur.find('.resize'), cur);
    });
});

// Update sliders on resize. 
$(window).resize(function () {
    $('.ba-slider').each(function () {
        var cur = $(this);
        var width = cur.width() + 'px';
        cur.find('.resize img').css('width', width);
    });
});

function drags(dragElement, resizeElement, container) {

    // Initialize the dragging event on mousedown.
    dragElement.on('mousedown touchstart', function (e) {

        dragElement.addClass('draggable');
        resizeElement.addClass('resizable');

        // Check if it's a mouse or touch event and pass along the correct value
        var startX = (e.pageX) ? e.pageX : e.originalEvent.touches[0].pageX;

        // Get the initial position
        var dragWidth = dragElement.outerWidth(),
            posX = dragElement.offset().left + dragWidth - startX,
            containerOffset = container.offset().left,
            containerWidth = container.outerWidth();

        // Set limits
        minLeft = containerOffset + 10;
        maxLeft = containerOffset + containerWidth - dragWidth - 10;

        // Calculate the dragging distance on mousemove.
        dragElement.parents().on("mousemove touchmove", function (e) {

            // Check if it's a mouse or touch event and pass along the correct value
            var moveX = (e.pageX) ? e.pageX : e.originalEvent.touches[0].pageX;

            leftValue = moveX + posX - dragWidth;

            // Prevent going off limits
            if (leftValue < minLeft) {
                leftValue = minLeft;
            } else if (leftValue > maxLeft) {
                leftValue = maxLeft;
            }

            // Translate the handle's left value to masked divs width.
            widthValue = (leftValue + dragWidth / 2 - containerOffset) * 100 / containerWidth + '%';

            // Set the new values for the slider and the handle. 
            // Bind mouseup events to stop dragging.
            $('.draggable').css('left', widthValue).on('mouseup touchend touchcancel', function () {
                $(this).removeClass('draggable');
                resizeElement.removeClass('resizable');
            });
            $('.resizable').css('width', widthValue);
        }).on('mouseup touchend touchcancel', function () {
            dragElement.removeClass('draggable');
            resizeElement.removeClass('resizable');
        });
        e.preventDefault();
    }).on('mouseup touchend touchcancel', function (e) {
        dragElement.removeClass('draggable');
        resizeElement.removeClass('resizable');
    });
}

干杯

【问题讨论】:

    标签: javascript jquery css


    【解决方案1】:

    如果滑块达到最大值,标签将被隐藏,否则将显示为块

    if (leftValue === minLeft)
      document.getElementById("leftElement").style.display = 'none';
    else      
      document.getElementById("leftElement").style.display = 'block';`
    

    出于演示目的,我将最大值和最小值更改为 +- 80,以便更明显。

    $(document).ready(function() {
      $(".ba-slider").each(function() {
        var cur = $(this);
        // Adjust the slider
        var width = cur.width() + "px";
        cur.find(".resize img").css("width", width);
        // Bind dragging events
        drags(cur.find(".handle"), cur.find(".resize"), cur);
      });
    });
    
    // Update sliders on resize.
    $(window).resize(function() {
      $(".ba-slider").each(function() {
        var cur = $(this);
        var width = cur.width() + "px";
        cur.find(".resize img").css("width", width);
      });
    });
    
    function drags(dragElement, resizeElement, container) {
      // Initialize the dragging event on mousedown.
      dragElement
        .on("mousedown touchstart", function(e) {
          dragElement.addClass("draggable");
          resizeElement.addClass("resizable");
    
          // Check if it's a mouse or touch event and pass along the correct value
          var startX = e.pageX ? e.pageX : e.originalEvent.touches[0].pageX;
    
          // Get the initial position
          var dragWidth = dragElement.outerWidth(),
            posX = dragElement.offset().left + dragWidth - startX,
            containerOffset = container.offset().left,
            containerWidth = container.outerWidth();
    
          // Set limits
          minLeft = containerOffset + 80;
          maxLeft = containerOffset + containerWidth - dragWidth - 80;
       
    
          // Calculate the dragging distance on mousemove.
          dragElement
            .parents()
            .on("mousemove touchmove", function(e) {
              // Check if it's a mouse or touch event and pass along the correct value
              var moveX = e.pageX ? e.pageX : e.originalEvent.touches[0].pageX;
    
              leftValue = moveX + posX - dragWidth;
    
              // Prevent going off limits
              if (leftValue <= minLeft) {
                leftValue = minLeft;
              } else if (leftValue > maxLeft) {
                leftValue = maxLeft;
              }
            
              if (leftValue === minLeft)
                 document.getElementById("leftElement").style.display = 'none';
              else      
                 document.getElementById("leftElement").style.display = 'block';
            
             if (leftValue === maxLeft)
                document.getElementById("rightElement").style.display = 'none';
             else      
                document.getElementById("rightElement").style.display = 'block';
          
            
    
              // Translate the handle's left value to masked divs width.
              widthValue =
                (leftValue + dragWidth / 2 - containerOffset) *
                  100 /
                  containerWidth +
                "%";
    
              // Set the new values for the slider and the handle.
              // Bind mouseup events to stop dragging.
              $(".draggable")
                .css("left", widthValue)
                .on("mouseup touchend touchcancel", function() {
                  $(this).removeClass("draggable");
                  resizeElement.removeClass("resizable");
                });
              $(".resizable").css("width", widthValue);
            })
            .on("mouseup touchend touchcancel", function() {
              dragElement.removeClass("draggable");
              resizeElement.removeClass("resizable");
            });
          e.preventDefault();
        })
        .on("mouseup touchend touchcancel", function(e) {
          dragElement.removeClass("draggable");
          resizeElement.removeClass("resizable");
        });
    }
    .rinse-away-container {
      margin-bottom: 8rem;
    }
    @media (min-width: 768px) {
      .rinse-away-container {
        margin-bottom: 10rem;
      }
    }
    @media (min-width: 992px) {
      .rinse-away-container {
        margin-bottom: 15rem;
      }
    }
    .ba-slider {
      position: relative;
      overflow: hidden;
      max-width: 1045px;
      margin: 5rem auto 0;
    }
    .ba-slider img {
      width: 100%;
      display: block;
    }
    .ba-slider .label-left,
    .ba-slider .label-right {
      position: absolute;
      bottom: 0;
      z-index: 2;
      padding: 1rem;
      color: white;
    }
    .ba-slider .label-right {
      right: 0;
    }
    .resize {
      position: absolute;
      top: 0;
      left: 0;
      height: 100%;
      width: 50%;
      overflow: hidden;
    }
    .handle {
      position: absolute;
      left: 50%;
      top: 0;
      bottom: 0;
      width: 1px;
      margin-left: -2px;
      background: #fff;
      cursor: ew-resize;
    }
    
    .handle:after {
      position: absolute;
      top: 50%;
      left: 50%;
      width: 10px;
      height: 64px;
      margin: -32px 0 0 -5px;
      content: "";
      color: white;
      text-align: center;
      background: #fff;
      -webkit-transition: all 0.3s ease;
      transition: all 0.3s ease;
    }
    
    .draggable:after {
      width: 30px;
      height: 64px;
      margin: -32px 0 0 -15px;
    }
    <!doctype html>
    <html lang="en">
    
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    
      <title></title>
    </head>
    
    <body>
      <div class="rinse-away-container">
        <div class="container rinse-away-content">
          <div class="compare-image-container">
            <div class="ba-slider">
              <img src="https://i.ibb.co/8cC5xQh/test1.png" alt="Test 1">
              <div id="leftElement" class="label-left">Text Left</div>
              <div class="resize">
                <img src="https://i.ibb.co/FkQQJ8j/test2.png" alt="Test 2">
              </div>
              <div id="rightElement" class="label-right">Text Right</div>
              <span class="handle"></span>
            </div>
          </div>
        </div>
      </div>
    
      <!-- JavaScript -->
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    </body>
    
    </html>

    【讨论】:

    • 嗨@Elias 感谢您的完整解释。我测试了但是有一个问题,当鼠标离开比较区域时,隐藏的文本会再次出现。我找到了这个示例:codyhouse.co/demo/image-comparison-slider/index.html 显示了我也希望我的工作方式。不想使用 codyhouse 示例,因为它需要额外的 jquery。有没有一种方法可以隐藏文本,直到用户再次向右滑动(到达图像中心的某处),即,如果向左滑动,左侧文本将消失并保持隐藏,直到用户向右滑动.
    • 嗨@Elias,另一个问题是即使我的鼠标不在图像区域内,它也会跟踪鼠标,因此当用户将鼠标移出图像时会导致文本出现和消失。
    • @StrangeLove 这是我现在尝试的:jsfiddle.net/5vdqyupL/1 我在“mouseup”中移动了那个小逻辑,但仍有一些情况会崩溃,例如如果滑块到达最小/最大区域,标签发疯了,需要重新运行。 :(但我明天可能会看看
    • @StrangeLove 我认为它已经完成,测试是否有问题让我知道:jsfiddle.net/EliasBlack/h3mozdka/5 如果没问题,我将使用正确的解决方案编辑主要答案。
    • 感谢您的帮助。我试过但似乎没有用,即使我一直滑到最后,文字仍然存在。再次感谢您的帮助。接受你的答案,因为它接近我想要的。
    【解决方案2】:

    只需根据方向检查您的鼠标移动功能,隐藏或显示标签。

    dragElement
      .parents()
      .on("mousemove touchmove", function(e) {
      // Check if it's a mouse or touch event and pass along the correct value
      var moveX = e.pageX ? e.pageX : e.originalEvent.touches[0].pageX;
      if(moveX < startX) {
        //dragleft
        $('.label-left').hide();
        $('.label-right').show();
      }else{
        //dragtight
        $('.label-right').hide();
        $('.label-left').show();
      }
    

    【讨论】:

    • 嗨@Lapskaus,我怎样才能使当用户滑回图像中心时,两个文本都会再次出现?
    • 将滑块的初始位置存储在一个变量中,并在 mousemove 侦听器中检查滑块是否回到其原始中心位置。您可以定义一个偏移量到它“捕捉”回中间的那个位置
    猜你喜欢
    • 2015-04-05
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    • 2020-08-31
    • 1970-01-01
    相关资源
    最近更新 更多