javascript – 如何防止父容器滚动定位为固定的子元素

我有一个父母和孩子.当用户滚动它时,子项具有’overflow:auto’属性,在结束后,父项开始滚动.怎么预防这个?

即使在子卷轴结束后,我也不要求父容器滚动.

这是代码:

.children{
  height:20em;
  overflow:auto;
  border:2px solid green;
  position:fixed;
  left:0;
  background:gray;
  z-index:100;
}

我有一些很大的内容来展示这个问题,所以请访问链接并滚动孩子们(灰色背景)

Live Demo

最佳答案 这是浏览器的默认行为.

为了防止这种情况,请检查Leland Kwong的这个编码器.

http://codepen.io/LelandKwong/pen/edAmn

   var trapScroll;

(function($){  

  trapScroll = function(opt){

    var trapElement;
    var scrollableDist;
    var trapClassName = 'trapScroll-enabled';
    var trapSelector = '.trapScroll';

    var trapWheel = function(e){

      if (!$('body').hasClass(trapClassName)) {

        return;

      } else {  

        var curScrollPos = trapElement.scrollTop();
        var wheelEvent = e.originalEvent;
        var dY = wheelEvent.deltaY;

        // only trap events once we've scrolled to the end
        // or beginning
        if ((dY>0 && curScrollPos >= scrollableDist) ||
            (dY<0 && curScrollPos <= 0)) {

          opt.onScrollEnd();
          return false;

        }

      }

    }

    $(document)
      .on('wheel', trapWheel)
      .on('mouseleave', trapSelector, function(){

        $('body').removeClass(trapClassName);

      })
      .on('mouseenter', trapSelector, function(){   

        trapElement = $(this);
        var containerHeight = trapElement.outerHeight();
        var contentHeight = trapElement[0].scrollHeight; // height of scrollable content
        scrollableDist = contentHeight - containerHeight;

        if (contentHeight>containerHeight)
          $('body').addClass(trapClassName); 

      });       
  } 

})($);

var preventedCount = 0;
var showEventPreventedMsg = function(){  
  $('#mousewheel-prevented').stop().animate({opacity: 1}, 'fast');
}
var hideEventPreventedMsg = function(){
  $('#mousewheel-prevented').stop().animate({opacity: 0}, 'fast');
}
var addPreventedCount = function(){
  $('#prevented-count').html('prevented <small>x</small>' + preventedCount++);
}

trapScroll({ onScrollEnd: addPreventedCount });
$('.trapScroll')
  .on('mouseenter', showEventPreventedMsg)
  .on('mouseleave', hideEventPreventedMsg);      
$('[id*="parent"]').scrollTop(100);

希望这对你有所帮助! 🙂

点赞