javascript - Target a specific div to scroll even outside of it - Stack Overflow

If I point the mouse within the div tag, the scrolling works, however I can't scroll the content i

If I point the mouse within the div tag, the scrolling works, however I can't scroll the content if I point the mouse outside the box of div. Is it possible to target a specific div wherever the mouse pointer goes?

<div style="max-height: 100px;overflow-y: scroll;">
  TEST<br><br><br><br><br><br><br><br><br><br>
</div>

If I point the mouse within the div tag, the scrolling works, however I can't scroll the content if I point the mouse outside the box of div. Is it possible to target a specific div wherever the mouse pointer goes?

<div style="max-height: 100px;overflow-y: scroll;">
  TEST<br><br><br><br><br><br><br><br><br><br>
</div>

Share Improve this question edited Aug 21, 2018 at 6:32 Chaska 3,2151 gold badge13 silver badges17 bronze badges asked Aug 21, 2018 at 6:27 Ninja Warrior 11Ninja Warrior 11 3723 silver badges17 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

You can do something like this.

const target = document.getElementById("target");

document.addEventListener("wheel", function(e){
  // prevent the default scrolling event
  e.preventDefault();

  // scroll the div
  target.scrollBy(e.deltaX, e.deltaY);
})
#target{
  height: 100px;
  overflow-y: scroll;
}
<div id="target">
  TEST<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</div>

You can register the event by yourselves. Such that you can scroll the div you want outside the div.

Those this will be tedious for you to handle if your page has multiple scroller.

By the way, to make it a bit more pretty, you need to add animation or it will move 'discretely' as following shown.

document.getElementById("scroll").addEventListener("wheel", e=>e.preventDefault());
document.getElementById("main").addEventListener("wheel", e=>myFunction(e));

function myFunction(e) {
    document.getElementById("scroll").scrollTop += 0.2 * e.deltaY;
}
<div id="main" style="height:300px">
<div id="scroll" style="max-height: 100px;overflow-y: scroll;">
  TEST<br><br><br><br><br><br><br><br><br><br>
</div>
</div>

Is it possible to target a specific div wherever the mouse pointer goes?

Not really... what you probably want to do instead is to set other parts of the page to position: fixed or position: sticky. This way the main body content will scroll but some parts will remain in the same place. Stack Overflow itself does this with the top header and the left sidebar.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745600107a4635350.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信