简体   繁体   English

仅滚动页内元素,而不是整页

[英]Scroll in-page element only, not the whole page

Ever notice that, when you're scrolling an overflowed div or textarea with a mousewheel, and you scroll that to the bottom, the whole page starts scrolling? 有没有注意到,当你用鼠标滚轮滚动溢出的div或textarea,并将其滚动到底部时,整个页面开始滚动?

Can that be prevented? 可以预防吗?

I did a quick test of jQuery's scroll() event handler but it seems to fire way too late. 我对jQuery的scroll()事件处理程序进行了快速测试,但它似乎太迟了。

Here's the test code if you want to play around. 如果你想玩游戏,这是测试代码。

<html>
<head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"></script>
  <script type="text/javascript" charset="utf-8">
  $(function() {
    $('#scroller').scroll(function() {
      $('#notification').css('display','block').fadeOut();
      return false;
    })
  })
  </script>
</head>
<body style="height: 2000px">
  <div id="scroller" style="width: 500px; height: 500px; overflow: scroll; margin: 50px">
    <div style="width: 1000px; height: 1000px; background: #ddd"></div>
  </div>
  <div id="notification" style="display:none">Bang</div>
</body>
</html>

This JS will do it, basically just set the body overflow to hidden when the mouse is over the div#scroller then set it back to normal when you mouse out. 这个JS会这样做,基本上只是当鼠标悬停在div#scroller上时将body溢出设置为隐藏,然后在鼠标移出时将其设置回正常状态。

$("#scroller").hover(
  function () {
        $('body').css('overflow','hidden');
  }, 
  function () {
        $('body').css('overflow','auto');
  }
);

Tested on Safari, Firefox and IE8 在Safari,Firefox和IE8上测试过

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM