简体   繁体   中英

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. 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. 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() ?

I think your code would look like this (no need for a getPosition function):

function goToUser(userName){
    $('div.popupNotifications input#' + username).closest('div').scrollIntoView();
}

如果列表中所有项目的高度均相同,则可以通过(索引+ 1)*项目高度来计算。

You can use the offset().top of the specific element.

function goToUser(userName) {
    var userPosition = getPosition(userName);
    $('.popupNotifications').scrollTop(userPosition);
}

function getPosition(userName){
    return $('.popupNotifications label:contains(' + userName + ')').offset().top;
}

Example fiddle

You could assign the element containing your user an ID or some class that identifies it (either id="user1" or class="user1")

Then you can simply use

$('#elementcontainingusers').scrollTop($('#user1').position().top);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM