2017-04-27 12 views
0

我剛剛創建了一個基本的Web聊天應用程序,問題是每當用戶發送消息時頁面會自動滾動。 當我發送消息時頁面不會刷新,因此它不應向上滾動。任何想法如何解決這個問題?聊天的Web應用程序與Rails - 頁面自動滾動發送消息時

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

回答

1

如果你想讓它留在頁面底部你可以使用像這樣的東西:

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

你叫每個消息被追加

0

這是一個用戶界面的問題,你可以解決它無論是在Javascript或CoffeeScript的代碼一次。

創建一個函數,它將識別您想要的div。
「消息追加」 這個你的情況和使用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(); 
});