JQuery滚动ID到顶部的div [英] JQuery scroll li id to top of div
问题描述
我正在使用JQuery将选定的列表项滚动到一个div中,并将溢出设置为滚动。下面的代码工作正常,但它将选定的列表项目滚动到屏幕顶部,而不是 #QuestionScroller
div的顶部。这使得它在上面的内容中不可见。我添加了 75px
偏移量,但这并不理想,因为上述内容的高度可能因视口大小而异。那么如何让脚本适应滚动到 #QuestionScroller
div的顶部不是页面顶部?
$(window).load(function(){
var contactTopPosition = $(#ListItemQuestion<%= Session [QuestionID]%>)。position() 75;
$(#QuestionScroller)。animate({scrollTop:contactTopPosition},2500);
});
请参阅下面的代码。希望这会对你有所帮助。
container.animate({scrollTop:scrollTo.offset()。top - container.offset()。top + container.scrollTop()});
#QuestionScroller {width:200px;身高:70px;边框:1px纯蓝色; overflow:auto;}
< script src =https ://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js>< / script>< div id =QuestionScroller> < UL> < li id ='row_1'> 111111< / li> < li id ='row_2'> 222222< / li> < li id ='row_3'> 333333< / li> < li id ='ListItemQuestion'> 444444< / li> < li id ='row_5'> 555555< / li> < li id ='row_6'> 666666< / li> < li id ='row_7'> 777777< / li> < li id ='row_8'> 888888< / li> < li id ='row_9'> 999999< / li> < / div>
I am using JQuery to scroll a selected list item into view within a div where the overflow is set to scroll. The following code works OK but it scrolls the selected list item to the top of the screen not the top of #QuestionScroller
div. This puts it out of view under the content above. I added 75px
offset but this is not ideal as the height of the content above can change depending on viewport size. So how to adapt the script to scroll to top of #QuestionScroller
div not top of page?
$(window).load(function () {
var contactTopPosition = $("#ListItemQuestion<%=Session["QuestionID"] %>").position().top - 75;
$("#QuestionScroller").animate({ scrollTop: contactTopPosition },2500);
});
See the code below. Hope this will be helpful for you.
var container = $('#QuestionScroller'),
scrollTo = $('#ListItemQuestion');
container.animate({scrollTop: scrollTo.offset().top - container.offset().top +
container.scrollTop()});
#QuestionScroller {
width: 200px;
height: 70px;
border: 1px solid blue;
overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="QuestionScroller">
<ul>
<li id='row_1'>111111</li>
<li id='row_2'>222222</li>
<li id='row_3'>333333</li>
<li id='ListItemQuestion'>444444</li>
<li id='row_5'>555555</li>
<li id='row_6'>666666</li>
<li id='row_7'>777777</li>
<li id='row_8'>888888</li>
<li id='row_9'>999999</li>
</ul>
</div>
这篇关于JQuery滚动ID到顶部的div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!