How to use text-input to go to anchor?

2019-04-15 02:51发布

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?

4条回答
家丑人穷心不美
2楼-- · 2019-04-15 03:28

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;
    });
});
查看更多
孤傲高冷的网名
3楼-- · 2019-04-15 03:34

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"

查看更多
三岁会撩人
4楼-- · 2019-04-15 03:37

Simply do:

var url = $('#gotoanchorinput').val();    
$(location).attr('href',url);
查看更多
一夜七次
5楼-- · 2019-04-15 03:49
    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.

查看更多
登录 后发表回答