简体   繁体   English

附加 <li> 到底部 <ul>

[英]Append <li> to the bottom of the <ul>

This is my code: 这是我的代码:

var message;
var ul = $('.chat');
var btn = $('#btnEnviar');

btn.click(()=>{
  message = $('#Mensaje').val()
  ul.append('<li>'+message+'</li>');
})
$('#Mensaje').keyup((e)=>{
  (e.which === 13) && ul.append('<li>'+$('#Mensaje').val()+'</li>')
})

rest of the code is here:
[https://codepen.io/willmsha/pen/zyQVPb][1]

As you guys can see that I have to scroll down after few times of adding new message to the ul. 你们可以看到,在向ul添加新消息几次后,我必须向下滚动。

Is there any chance to prevent that except using something like this: 除了使用类似这样的方法外,还有什么机会防止这种情况发生:

window.scrollTo(0,document.body.scrollHeight);



So what I wanna do is something like to append the li tag to the bottom of the ul, so I wont have to scroll down when a new mesage is added. 所以我想做的是将li标签附加到ul的底部,因此添加新消息时不必向下滚动。

Just use the .scrollIntoView() method. 只需使用.scrollIntoView()方法。 Add this to your btn.click listener: 将此添加到您的btn.click侦听器:

var children = document.getElementsByClassName("chat")[0].childNodes;

children[children.length-1].scrollIntoView();

Read more about it here: https://www.w3schools.com/jsref/met_element_scrollintoview.asp 在此处阅读有关此内容的更多信息: https : //www.w3schools.com/jsref/met_element_scrollintoview.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM