简体   繁体   中英

Javascript onclick window.location for page anchors?

So SOF,

I've got a little problem where I don't want #BOT to appear in my url when I click my links when using page anchors.

Javascript

$("a.bottom").click(function() {
    window.location = '#BOT';
});

Different links...

<a class="bottom" href="javascript: void(0);">BOTTOM</a>
<a href="#BOT">BOTTOM</a>

Anchor

<a id="KEY"></a>

How do I stop it adding #BOT in the pageurl bar?

The jQuery scrollTo plugin is very good at this. It will scroll your window to an element without using anchors:

$("a.bottom").click(function() {
    $.scrollTo($("a[name='#BOT']"));
});

Would be good to make the functionality more generic too:

jQuery

$("a.scrollable").click(function() {
    $.scrollTo($("#"+$(this).data("scrollto")));
});

HTML

<a class="scrollable" data-scrollto="BOT">BOTTOM</a>
<a id="BOT"></a>
<a class="scrollable" data-scrollto="KEY">BOTTOM</a>
<a id="KEY"></a>

This can be done using jQuery offset and animate as discussed in this question

function scrollToAnchor(aid) {
    var aTag = $("a[id='" + aid + "']");
    $('html,body').animate({
        scrollTop: aTag.offset().top
    }, 'slow');
}

$("a.bottom").click(function () {
    scrollToAnchor('BOT');
});

Fiddle here

You can scroll the page by using window.scrollTo(x,y) method. Which does not need page to be refreshed.

for example:

$("a.bottom").click(function() {
    scrollTo(0,100);
});

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