与Rails聊天网络应用 - 发送消息时页面自动滚动



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

部分_new_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 %>

部分_message.html.erb

<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>

javascript

received: function(data) {
    // Called when there's incoming data on the websocket for this channel
    $('.message-append').append(data.message);
  },
  listen_to_messages: function() {
    return this.perform('listen', {
      room_id: $("[data-room-id]").data("room-id")
    });
  }
});
$(document).on('turbolinks:load', function() {
  App.room.listen_to_messages();
});

如果您希望它留在页面底部,则可以使用类似的东西:

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

您每次附加消息时都称其为

这是一个UI问题,您可以在JavaScript或Coffeescript代码中解决它。

创建一个函数,可以识别您所需的div。

  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();
  },

类似地更新您的涡轮链接:加载

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

最新更新