如何通过jquery将HTML内容附加到底部时将div保持滚动到底部,但隐藏滚动条?
下面我有一个基于小js的模拟器,用于不同的命令工具。 用户输入命令,如果正确,则将其显示在顶部。 为了将来的使用,我需要确保在完成模拟之前它可以根据需要处理尽可能多的命令。 这意味着我不可避免地会有内容溢出。
我现在的解决方案是将Y溢出设置为auto,添加滚动条和一个小jquery以使客户端始终滚动到输出div的底部,因为每次用户输入时内容都会附加到先前内容的下方正确的命令。
现在这个工作正常,除了我想删除滚动条。 除了没有可见的滚动条之外,我希望内容的行为方式与溢出auto一样。
有没有办法用jquery或javascript做到这一点?
我知道我可以用一些css技巧在滚动条上放一些带有z-index的黑色,但我想尽可能避免这种情况。
您只需要向容器中添加overflow: hidden
并在加载内容后滚动它:
div.scrollTop = div.scrollHeight;
演示http://jsfiddle.net/nT75k/2/
是的,您可以添加一个事件监听器,当该事件发出时,您可以通过检查高度向下滚动到底部
$container = $('.container'); $container[0].scrollTop = $container[0].scrollHeight; $('.input').keypress(function (e) { if (e.which == 13) { $container = $('.container'); $container.append('' + e.target.value + '
'); $container.animate({ scrollTop: $container[0].scrollHeight }, "slow"); } });
继续使用javascript进行滚动,并将包含模拟器的div放在另一个稍微不宽的div中,并在外部div上隐藏溢出。 我已经使用过这种技术几次了,这很有趣。
你唯一要注意的是滚动条在不同的浏览器中的宽度略有不同,所以要小心。
例如:
HTML:
more content 1 more content 2 more content 3 more content 4 more content 5 more content 6 more content 7 more content 8 more content 9 more content 8 more content 7 more content 6 more content 5 more content 4 more content 3 more content 2 more content 1
CSS:
div#outside { width: 120px; height: 100px; overflow: hidden; } div#inside { width: 135px; height: 100px; overflow-y: auto; }
看看这个小提琴 – > http://jsfiddle.net/5bkz5/1/ < - 然后向下滚动文本!
div.scrollTop = div.scrollHeight;
但你不需要overflow: hidden
。