代码之家  ›  专栏  ›  技术社区  ›  Stark

使用mousemove时如何阻止div向上移动?

  •  0
  • Stark  · 技术社区  · 6 年前

    我试图防止盒子被拉起,但可以被拉下,这是我想到的,但我不知道如何保持原始位置,所以我有一个参考添加到if检查。它仅在主体滚动一点后出现。

    jsfiddle

    window.addEventListener("scroll",function(){
      if($(document).scrollTop() > 100){
        $( ".box" ).slideDown({
          start: function () {
            $(this).css({
              display: "flex"
            })
          }
        });    
      }
    
      var top = 0;
      var divOverlay = document.getElementsByClassName('box')[0];
      var is_clicked = false;
    
      divOverlay.addEventListener('mousedown', function(e){   
        is_clicked = true;
        top = divOverlay.offsetTop - e.clientY
      }, true);
    
      document.addEventListener('mouseup', function(){
        is_clicked = false;
      }, true);
    
      document.addEventListener('mousemove', function(e){  
        event.preventDefault();
    
        // add a check here so it doesn't allow dragging the container up?
        if(is_clicked){
          divOverlay.style.top  = (e.clientY + top) + 'px';
    
          // if the box reaches 50px down, it should automatically hide it if the user
          //$('.box').slideUp();
        }
      }, true);
    
    })
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   pl61    6 年前

    你可以尝试使用 Math.max 要将长方体的最大顶部位置限制为视口高度减去长方体高度,请执行以下操作:

    document.addEventListener('mousemove', function(e){
      event.preventDefault();
    
      // add a check here so it doesn't allow dragging the container up?
      var maxTop = window.innerHeight - divOverlay.offsetHeight;
      if(is_clicked){
        divOverlay.style.top  = Math.max(maxTop, e.clientY + top) + 'px';
    
        // if the box reaches 50px down, it should automatically hide it if the user
        //$('.box').slideUp();
      }
    }, true);