使用Rails聊天Web应用程序 - 发送消息时页面自动滚动

时间:2017-04-27 08:48:06

标签: javascript jquery ruby-on-rails actioncable

我刚创建了一个基本的网络聊天应用程序,问题是每次用户发送消息时页面会自动向上滚动。 发送邮件时页面不刷新,因此不应向上滚动。知道如何解决这个问题吗?

部分_new_message.html.erb

token.username or token.country

部分_message.html.erb

<% if signed_in? %>
  <%= form_for([@room, @room.messages.build], remote: true) do |f| %>
  <div class="row">
    <div class="message-area col-xs-10 col-sm-10 col-md-11">
      <%= f.text_area :body, class: 'form-control', placeholder:'Type your message..', id:'exampleTextarea', rows:'2' %>
    </div>
    <span>
      <%= button_tag "", type: 'submit', class: "btn btn-default glyphicon glyphicon-send send-message col-xs-2 col-sm-2 col-md-1" %>
      <!-- <%= f.submit "Submit", class:'btn btn-primary send-message col-md-1' %> -->
    </span>
  </div>
  <% end %>
<% end %>

的Javascript

<div class="message-append">
  <% @messages.each do |message| %>
  <div class="message-wrap"><%= message.user.user_name %>: <%= message.body %>
    <% if signed_in? && current_user.admin? %>
      <%= link_to ('<span class="glyphicon glyphicon-remove"></span>').html_safe, room_message_path(message.room, message), method: :delete, data: { confirm: 'Are you sure?' } %>
    <% end %>
  </div>
  <div class="message-divider"></div>
  <% end %>
</div>

2 个答案:

答案 0 :(得分:1)

如果您希望它保留在页面底部,您可以使用以下内容:

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

每次附加邮件时都会调用它

答案 1 :(得分:1)

这是一个UI问题,你可以用Javascript或coffeescript代码解决它。

创建一个能够识别所需div的功能。
&#34; message-append&#34;在你的情况下,使用如下的StrollTop:

  scroll_bottom: function() {
    $('.message-append').scrollTop($('.message-append')[0].scrollHeight)
  }

您需要更新接收方式:

 received: function(data) {
    // Called when there's incoming data on the websocket for this channel
    $('.message-append').append(data.message);
    scroll_bottom();
  },

同样更新您的Turbolinks:加载

 $(document).on('turbolinks:load', function() {
  App.room.listen_to_messages();
  scroll_bottom();
});