【问题标题】:Chat web app with Rails - page auto scroll when sending message使用 Rails 聊天 Web 应用程序 - 发送消息时页面自动滚动
【发布时间】:2017-04-27 08:48:05
【问题描述】:

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

部分 _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();
});

【问题讨论】:

    标签: javascript jquery ruby-on-rails actioncable


    【解决方案1】:

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

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

    每次附加消息时都调用它

    【讨论】:

      【解决方案2】:

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

      创建一个函数来识别您想要的 div。
      “message-append”在您的情况下并使用 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:loads

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

      【讨论】:

        猜你喜欢
        • 2020-09-03
        • 1970-01-01
        • 2020-01-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-27
        • 2015-10-04
        • 1970-01-01
        相关资源
        最近更新 更多