简体   繁体   中英

jQuery scrollTop and focus on element

I have the following scrollTop function:

<a onclick="jQuery('html,body').animate({scrollTop:0},'slow');return false;" class="well well-sm" href="#">
                    <i class="uxf-icon uxf-up-open-large"></i><span class="sr-only">${message:backToTop}</span></a>

However, when you use your keyboard to navigate the focus does not go to the top. It remains in the footer. Is there a way to bring the focus to the following div:

<div id="top" tabindex="-1"></div>

The visual focus is different from the keyboard focus, you can use the focus() function to define the keyboard focus

 <a onclick="jQuery("#top").focus();return false;" class="well well-sm" href="#">...</a>

This can be used conjointly with your animate function.

Animated scrolling to the top of the element, then setting a focus:

<script>
    function scroll() {
        $('html, body').animate({
            scrollTop: $('#top').offset().top
        }, 'slow', function() { 
            $('#top').focus(); 
        });
    }
</script>
<a onclick="scroll(); return false;" class="well well-sm" href="#">...</a>

The problem is that you have assignd a click to it, while enter is a keypress, you have to set it both, here's one way to do it with jQuery delegation:

function animateToTop() {
    $('html,body').animate({
        scrollTop: $('#top').offset().top
    }, 'slow');
}

$('#aSendToTop').on('click keypress',
    function (e) {
        // mouse 1 has keyCode 1, while enter is keycode 13
        if( [1, 13].indexOf(e.which) > -1 ) animateToTop();
    }
);

JSFiddle

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