为html <a> tags from javascript

时间:2016-07-09 22:45:01

标签: javascript html

I have this function that I found online that causes the href in my tags to be scrolled to rather than just appear there:

$(function () {
    var headerHeight = 70;
    $('a[href*=#]:not([href=#])').click(function () {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
            if (target.length) {
                $('html,body').animate({
                    scrollTop: target.offset().top - headerHeight
                }, 1000);
                return false;
            }
        }
    });
});

Now I need to get to a location in the page by using javascript code because I have an awkward situation where the form submit button should also scroll to a location:

        <div  
            value="GO"
            id="go-div"
            class="bubble">

            <input  type="submit" 
                    value="GO"
                    id="go-button"
                    style="    position: absolute;
                                width: 100%;
                                height: 100%;
                                top: 0;
                                left: 0;"

                onclick="location.href='#search-results-page';">
            </input>
        </div>

So how do I change the location.href='#search-results-page'; to use the scrolling function?

1 个答案:

答案 0 :(得分:2)

有多种方法可以做到这一点。以下是一个示例:https://jsfiddle.net/nx7xf1nb/

$(function () {
    var headerHeight = 70;
    $('a[href*="#"]:not([href="#"])').click(function () {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
            if (gotoTarget(this.hash))
                return false;
        }
    });

    $('input[data-target]').click(function() {
        if (gotoTarget($(this).data("target")))
            return false;
    })

    function gotoTarget(targetName) {
        var target = $(targetName);
        target = target.length ? target : $('[name="' + targetName.slice(1) + '"]');
        if (target.length) {
            $('html,body').animate({
                scrollTop: target.offset().top - headerHeight
            }, 1000);

            return true;
        }

        return false;
    }
});

按钮:

<input style="position: absolute; width: 100%; height: 100%; top: 0; left: 0;"
       type="submit" 
       data-target="#search-results-page"
       value="GO"
       id="go-button">