How to use text-input to go to anchor?

不羁的心 提交于 2019-12-06 12:12:04

问题


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);


来源:https://stackoverflow.com/questions/12250396/how-to-use-text-input-to-go-to-anchor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!