求助:实现页面任意区域滚动时仅#container内容滚动的方案
实现页面任意区域滚动时同步滚动#container内容
我当前的HTML结构如下:
<body> <div id="dummy_top_frame"></div> <div id="frame"> <div id="container"> content </div> </div> </body>
对应的CSS样式:
html, body, #frame{ -ms-overflow-style: none; scrollbar-width: none; } body::-webkit-scrollbar, #frame::-webkit-scrollbar{ display: none; width: 0; height: 0; } body{ margin:0px; padding:0px; background:#333; } #dummy_top_frame{ position:absolute; top:40px; width:598px; height:150px; left:50%; margin-left:-300px; border:1px solid white; border-bottom:none; background:black; } #frame{ position:fixed; top:41px; width:600px; left:50%; margin-left:-300px; height: calc( 100% - 41px); overflow:scroll; } #container{ position:relative; width:598px; border:1px solid white; border-top:none; margin-bottom:140px; background:black; color:white; }
目前#container内部滚动鼠标时内容可正常滚动,但我希望无论鼠标在页面哪个区域滚动,都只让#container的内容随之上下滚动。
我尝试过以下jQuery代码,但无效:
$(window).scroll(function(){ $('#container').scrollTop($(this).scrollTop()); });
请问如何实现这一需求?
解决方案
你之前的代码无效的核心原因是:window.scroll事件仅在window本身产生滚动时才会触发,但你的页面中#frame是fixed定位,body没有可滚动的内容,所以该事件根本不会被触发。正确的做法是监听整个文档的滚轮动作事件,直接捕获鼠标滚动行为并同步到#container上。
使用以下jQuery代码即可实现需求:
$(document).ready(function() { $(document).on('wheel', function(e) { const $container = $('#container'); // 根据滚轮滚动方向计算新的滚动位置 const newScrollTop = $container.scrollTop() + e.originalEvent.deltaY; // 设置#container的滚动位置 $container.scrollTop(newScrollTop); // 阻止默认滚动行为,避免影响页面其他元素 e.preventDefault(); }); });
关键说明:
wheel事件会监听所有鼠标滚轮的滚动动作,无论鼠标在页面哪个区域e.originalEvent.deltaY表示滚轮滚动的距离,向下滚动为正,向上为负,直接累加到#container的scrollTop上即可实现同步滚动- 调用
e.preventDefault()可以阻止浏览器默认的滚动行为,确保只有#container的内容滚动
内容的提问来源于stack exchange,提问作者Bachir Messaouri
相关产品推荐
相关产品推荐

