简体   繁体   中英

How to set scroll position to the level of checked radio button?

在此处输入图片说明

As you see above, I have a small and narrow div and in this div there are radio buttons . One of the these radios is always checked . I want to set scroll bar's start position to the level of checked radio button when page loaded.

Is it possible? If yes, how can I do it?

fiddle: http://jsfiddle.net/ct346z65/

When the page loads you can filter through all the radio buttons and find the one that is checked. When you have that button you can just scroll to it with jQuery.

This is the code html:

<div id="radioContainer">
    <input type="radio" name="distance" value="1"/>1<br>
    <input type="radio" name="distance" value="2"/>2<br>
    <input type="radio" name="distance" value="3"/>3<br>
    <input type="radio" name="distance" value="4"/>4<br>
    <input type="radio" name="distance" value="5"/>5<br>
    <input checked type="radio" name="distance" value="6"/>7<br>
    <input type="radio" name="distance" value="8"/>8<br>
    <input type="radio" name="distance" value="9"/>10<br>
</div>

and the JS:

$(document).ready(function() {
    $('#radioContainer > input').each(function() {
        var radioInput = $(this);
        if(radioInput.is(':checked')) {
            $('#radioContainer').animate({
                scrollTop: radioInput.offset().top
            }, 2000);
        }
    });
});

Source for the jQuery scroll to animation: jQuery scroll to element

JSFiddle: http://jsfiddle.net/ct346z65/4/

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