我正在尝试模仿其他移动聊天应用程序,在这些应用程序中,当您选择send-message
文本框并打开虚拟键盘时,最底部的消息仍在显示中。似乎没有办法用CSS来做到这一点,所以JavaScript resize
(显然是找出何时打开和关闭键盘的唯一方法)是事件和手动滚动以进行救援。
有人提供了这个解决方案,我发现了这个解决方案,两者似乎都可以工作。
除了一种情况。出于某种原因,如果您位于MOBILE_KEYBOARD_HEIGHT
消息div底部(在我的情况下为250像素)以内,则当您关闭移动键盘时,会发生一些奇怪的情况。使用前一种解决方案,它会滚动到底部。使用后一种解决方案时,它会MOBILE_KEYBOARD_HEIGHT
从底部向上滚动像素。
如果滚动到该高度以上,则上面提供的两个解决方案都可以正常工作。只有当您接近底部时,他们才会遇到这个小问题。
我以为可能只是我的程序导致了一些奇怪的流浪代码,但不,我什至重现了一个小提琴,它确实有这个问题。我很抱歉使调试变得如此困难,但是如果您在手机上访问https://jsfiddle.net/t596hy8d/6/show(显示后缀提供全屏模式),您应该可以看到同样的行为。
如果您向上滚动足够,打开和关闭键盘将保持该位置。但是,如果将键盘关闭在MOBILE_KEYBOARD_HEIGHT
底部像素以内,则会发现它滚动到底部。
是什么原因造成的?
这里的代码复制:
window.onload = function(e){
document.querySelector(".messages").scrollTop = 10000;
bottomScroller(document.querySelector(".messages"));
}
function bottomScroller(scroller) {
let scrollBottom = scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight;
scroller.addEventListener('scroll', () => {
scrollBottom = scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight;
});
window.addEventListener('resize', () => {
scroller.scrollTop = scroller.scrollHeight - scrollBottom - scroller.clientHeight;
scrollBottom = scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight;
});
}
.container {
width: 400px;
height: 87vh;
border: 1px solid #333;
display: flex;
flex-direction: column;
}
.messages {
overflow-y: auto;
height: 100%;
}
.send-message {
width: 100%;
display: flex;
flex-direction: column;
}
<div class="container">
<div class="messages">
<div class="message">hello 1</div>
<div class="message">hello 2</div>
<div class="message">hello 3</div>
<div class="message">hello 4</div>
<div class="message">hello 5</div>
<div class="message">hello 6 </div>
<div class="message">hello 7</div>
<div class="message">hello 8</div>
<div class="message">hello 9</div>
<div class="message">hello 10</div>
<div class="message">hello 11</div>
<div class="message">hello 12</div>
<div class="message">hello 13</div>
<div class="message">hello 14</div>
<div class="message">hello 15</div>
<div class="message">hello 16</div>
<div class="message">hello 17</div>
<div class="message">hello 18</div>
<div class="message">hello 19</div>
<div class="message">hello 20</div>
<div class="message">hello 21</div>
<div class="message">hello 22</div>
<div class="message">hello 23</div>
<div class="message">hello 24</div>
<div class="message">hello 25</div>
<div class="message">hello 26</div>
<div class="message">hello 27</div>
<div class="message">hello 28</div>
<div class="message">hello 29</div>
<div class="message">hello 30</div>
<div class="message">hello 31</div>
<div class="message">hello 32</div>
<div class="message">hello 33</div>
<div class="message">hello 34</div>
<div class="message">hello 35</div>
<div class="message">hello 36</div>
<div class="message">hello 37</div>
<div class="message">hello 38</div>
<div class="message">hello 39</div>
</div>
<div class="send-message">
<input />
</div>
</div>