How to use text-input to go to anchor?

2019-04-15 03:43发布

问题:

I want to use jQuery to go to an anchor with the use of a textbox, for example, I want to use this form:

<form id="gotoanchorform">
    <input id="gotoanchorinput" type="text" />
    <input type="submit" value="Go to anchor" />
</form>

In this form I would type the name of the anchor and when I click the "Go to anchor" button or press the enter key I want the page to scroll down to that anchor:

<a name="targetAnchor" id="targetAnchor">Target</a>

How would get this to work with jQuery?

回答1:

    var anchor = $("#gotoanchorinput").val();
    var position = $("#"+anchor).offset();
    window.scrollTo(position.left, position.top);

This piece of code make your page scroll to the anchor written in #gotoanchorinput.



回答2:

try something like this:

$(function() {
    $('form#gotoanchorform').submit(function(e) {
        e.preventDefault();

        var desired = $('#gotoanchorinput').val();

        window.location.href = window.location.href + '#' + desired;

        // or

        $('html, body').animate({'scrollTop', $('a[name*="' + desired +'"').offset().top + 'px'}, 900);


        return false;
    });
});

so if you would type "foo" and click submit, the page would scroll to an which name attribute contains "foo"



回答3:

HTML part:

<form id="myForm" data-anchor="#myAnchor">
    <input type="text" />
    <input type="submit" value="Go to anchor" />
</form>

NB: data-x attribute is valid HTML.

JS part:

$(document).ready(function() {

    $('#myForm').submit(function(e){

        $(location).attr('href', $(this).attr('data-anchor'));

        return false;
    });
});


回答4:

Simply do:

var url = $('#gotoanchorinput').val();    
$(location).attr('href',url);