我有一个侧边栏 div,它会自动加载新消息,我试图让 div 自动滚动到发布的最后一条消息。这是 html
<div class="row">
<div class="column col-sm-4" id="sidebar">
<div class="message-wrap col-lg-12 col-md-6">
<div class="msg-wrap" id="msg-wrap">
<!-- start message loop -->
<div class="media msg">
<div class="media-body">
<small class="pull-right time"><i class="fa fa-clock-o"></i> 12:12:12pm</small>
<a class="pull-left" href="#">
<div class="thumbnail" style="margin:5px;"> {pic} </div>
</a>
<strong class="media-heading">Guy Faux</strong>
<small class="col-lg-9">Hi this is Guy and im typing a message about Fauxing</small>
</div>
</div>
<!-- end message loop -->
<!-- start message loop -->
<div class="media msg">
<div class="media-body">
<small class="pull-right time"><i class="fa fa-clock-o"></i> 12:12:12pm</small>
<a class="pull-left" href="#">
<div class="thumbnail" style="margin:5px;"> {pic} </div>
</a>
<strong class="media-heading">Guy Faux</strong>
<small class="col-lg-9">Hi this is Guy and im typing a message about Fauxing</small>
</div>
</div>
<!-- end message loop -->
<!-- start message loop -->
<div class="media msg">
<div class="media-body">
<small class="pull-right time"><i class="fa fa-clock-o"></i> 12:12:12pm</small>
<a class="pull-left" href="#">
<div class="thumbnail" style="margin:5px;"> {pic} </div>
</a>
<strong class="media-heading">Guy Faux</strong>
<small class="col-lg-9">Hi this is Guy and im typing a message about Fauxing</small>
</div>
</div>
<!-- end message loop -->
<!-- start message loop -->
<div class="media msg">
<div class="media-body">
<small class="pull-right time"><i class="fa fa-clock-o"></i> 12:12:12pm</small>
<a class="pull-left" href="#">
<div class="thumbnail" style="margin:5px;"> {pic} </div>
</a>
<strong class="media-heading">Guy Faux</strong>
<small class="col-lg-9">Hi this is Guy and im typing a message about Fauxing</small>
</div>
</div>
<!-- end message loop -->
</div>
</div>
</div>
我试过这个Js:
$(document).ready(function(){
var lastMsg = $('#msg-wrap .msg:last')
var scrollToElement = function(el, ms){
var speed = (ms) ? ms : 600;
$('html,body').animate({
scrollTop: $(el).offset().top
}, speed);
}
scrollToElement(lastMsg, 600);
});
我还尝试了在 Stack 上搜索过的几行不同的代码:
window.location.hash = lastMsg;
$('#msg-wrap .msg:last').focus();
$('#msg-wrap').animate({ scrollTop: lastMsg.offset().top }, 'fast');
$('html, body').animate({scrollTop:lastMsg.position().top}, 'slow');
无论我尝试什么,似乎都无济于事。有什么建议 ?
最佳答案
我对您的代码做了 2 处小改动,可以在 this fiddle 中找到工作:
var scrollToElement = function($el, ms){
var speed = (ms) ? ms : 600;
$('body').animate({ // only scroll the body element, the html element doesn't need to be scrolled at the same time
scrollTop: $el.offset().top // you're already passing a jquery object, no need to re-wrap it
}, speed);
}
关于javascript - 自动滚动到 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25234283/