当嵌套滚动中的数据发生更改时,阻止页面滚动
问题描述:
我在页面中有一个固定大小的元素,其中overflow:scroll内容经常更改。
我希望在这个元素中发生的变化会影响这个元素的滚动,但不会影响页面滚动。
I have a fixed-sized element in a page with "overflow: scroll" which content is changes often. I expect that changes happened inside this element can affect scroll of this element, but not a page scroll.
但是当页面顶部有这个元素时,页面本身开始滚动。如何防止这种情况?
But when this element on the top of the page, the page itself begin scroll. How can I prevent this?
要重现此行为(我在chrome中遇到此问题,但Firefox工作正常):
To reproduce this behaviour (I've got this problem in chrome, but Firefox works fine):
- 打开 https://jsfiddle.net/hd2Ltmu0/2 /
- 开始将页面滚动到灰色元素的中心
- 等一下,页面滚动会向上移动
代码示例:
<body>
<div style="overflow-y: scroll;height: 300px">
Content that changes often
</div>
Content that should not move even the upper block is changed
</body>
答
一个hacky解决方案是存储滚动的值在添加内容并在之后使用它之前:
one hacky solution is to store the value of the scroll before adding content and use it after:
setInterval(function() {
var s= $(window).scrollTop();
$('.scrollable').children().first().remove();
$('.scrollable').append('<div>'+(Date.now())+'</div>');
$(window).scrollTop(s);
}, 1000);
;
.demo {
font-size: 24px;
}
.scrollable {
height: 300px;
overflow-y: scroll;
background: #eee;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="demo">
String<br>
String<br>
String<br>
String<br>
<div class="scrollable">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>10</div>
<div>11</div>
<div>12</div>
<div>13</div>
<div>14</div>
<div>15</div>
</div>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
String<br>
</div>