[英]jQuery calculate position of item in scrollable window and scroll to it
there. 那里。 I have a list of items (users) in a popup. 我在弹出窗口中有一个项目(用户)列表。 This list is in a scrollable div. 此列表位于可滚动的div中。 I want to make a search box that, using jQuery and Javascript, calculates the position of the desired user in this list and then scrolls to it. 我要创建一个搜索框,使用jQuery和Javascript计算所需用户在此列表中的位置,然后滚动到该位置。 Basically, this is what I want: 基本上,这就是我想要的:
function goToUser(userName) {
var userPosition = getPosition(userName);
$('#myContainer').scrollTop(userPosition);
}
function getPosition(userName){
// ?????
}
Anyone had such a problem before ? 有人以前有过这样的问题吗? Thank you. 谢谢。
This is the partial view I use for the popup: 这是我用于弹出窗口的局部视图:
@using (@Html.BeginForm())
{
<div class="popupTitle">
Choose user(s)
</div>
<div style="height: 400px; overflow: scroll" class="popupNotifications">
@foreach (var user in Model.Users)
{
<div>
<input id="Users-@user.id" name="targetIds" type="checkbox" value="@user.id" @if(Model.TargetIds != null && Model.TargetIds.Contains(user.id)){<text>checked="checked"</text>} />
<label for="Users-@user.id" style="cursor: pointer;">@user.name</label>
</div>
}
</div>
<div class="popupButtons">
<input type="button" class="button" value="Save" onclick="GetValues(Notifications_UsersPopupHolder)" />
<input type="button" class="button" value="Cancel" onclick="Cancel(Notifications_UsersPopupHolder)" />
</div>
} }
Have you tried $(element).scrollIntoView()
? 您是否尝试过$(element).scrollIntoView()
?
I think your code would look like this (no need for a getPosition function): 我认为您的代码将如下所示(不需要getPosition函数):
function goToUser(userName){
$('div.popupNotifications input#' + username).closest('div').scrollIntoView();
}
如果列表中所有项目的高度均相同,则可以通过(索引+ 1)*项目高度来计算。
You can use the offset().top
of the specific element. 您可以使用特定元素的offset().top
。
function goToUser(userName) {
var userPosition = getPosition(userName);
$('.popupNotifications').scrollTop(userPosition);
}
function getPosition(userName){
return $('.popupNotifications label:contains(' + userName + ')').offset().top;
}
You could assign the element containing your user an ID or some class that identifies it (either id="user1" or class="user1") 您可以为包含用户的元素分配一个ID或标识它的某个类(id =“ user1”或class =“ user1”)
Then you can simply use 然后,您可以简单地使用
$('#elementcontainingusers').scrollTop($('#user1').position().top);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.