简体   繁体   中英

How do I prevent a hash tag link from scrolling the page?

This is driving me absolutely insane. I am building a very customized slider jQuery plugin for a project. One of my requirements is that users must be able to deep link into a specific slide. So naturally all of my slides have hash tags and the navigation links have corresponding hashtags. My problem is that the default functionality of the hash tag links are firing on top of my sliding animation triggered by javascript. That is, instead of sliding to slide 4 it jumps immediately to slide 4 and then animates to slide 8. This is despite using every trick I can think of to prevent the default functionality. Here is the snippet of code in question.

$(slider.nav).bind( 'click', function(event) {
    event.preventDefault();
    if( !$(this).hasClass('active') ) {
        var target = slider.nav.index( $(this) );
        slider.animate( target );
    }
});

As you can see here I have used event.preventDefault(). I have also tried returning false. No luck whatsoever. Any ideas?

It's hard to say without seeing the HTML. But if it's the way I imagine it, you don't need to keep href="#" in a link if it's not going anywhere. You can use jQuery to just get the next slide, or get slide number 7 without relying on href="#" links.

Instead, you can do something like:

<ul id="slideshow">
    <li id="slide_1">Slide 1</li>
    <li id="slide_2">Slide 2</li>
    <li id="slide_3">Slide 3</li> 
</ul>

<a class="slide_nav" data-index="1">1</a>
<a class="slide_nav" data-index="2">2</a>
<a class="slide_nav" data-index="3">3</a>
<a class="slide_nav" data-index="4">4</a>

And in the JS, do something like:

$('.slide_nav').click(function() {
    var slides = $('#slideshow li'); // get all slides
    var target_id = $(this).data('id') - 1; // Get the current ID and then subtract 1 (index starts at 0)
    slider.animate(slides[target_id]);
});

Anyway, that's more like a pseudo-example than anything else, and I'm not sure that would work as-is, but the code should hopefully point you in a direction that would avoid using href="#" and thus avoid the problem you're having now.

Good luck.

Oh jeeze. I'm really sorry. I've wasted everyone's time.

Apparently another developer who was working on the site had added some javascript elsewhere roughly to the effect of

if( window.location.hash ) {
    window.location = window.location.hash;
}

No idea why they would add such a thing. Sorry!

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