How to prevent jump on an anchor click?

早过忘川 提交于 2019-12-17 11:07:07

问题


I use e.preventDefault(); to disable default anchor behaviour.

Is there a way to prevent only jump action to a target on click?

I tried:

  var hash = window.location.hash;
  var link = $('a');
  $('a').click(function() {
    e.preventDefault();
    hash = "#"+link.attr("href");
  });

But it doesn't work: http://jsfiddle.net/ynts/LgcmB/.


回答1:


$(document).ready(function() {
  var hash = window.location.hash;
  var link = $('a');
  $('a').click(function(e) {
    e.preventDefault();
    hash = link.attr("href");
    window.location = hash;
  });
});

You also have to specify event argument in the function. By naming it as e or event and then you can manipulate it.




回答2:


This is the only solution I could come up with that works consistently across all desktop and mobile browsers with various client UI libraries and frameworks. By getting the window coordinates before scrolling occurs we can revert and maintain the current scroll position.

$('a').click(function (e) {
    var x = window.pageXOffset,
        y = window.pageYOffset;
    $(window).one('scroll', function () {
        window.scrollTo(x, y);
    })
});



回答3:


To only prevent the "jump" you have to use different id for the target element than what is specified in the anchor.

e.g. for a link to a new tab use,

<a href="#new" />

and for the target element mask the id

<div id="new-tab"></div>

Then in your script append the mask to the real hash, and use it to get the element.

$(window).on("hashchange", function(){
    var hash = this.location.hash;
    var mytab = $(hash + "-tab");
});

This preserves the hash location changes in browser history that can be controlled by the back/forward buttons, and detected on page load with the hashchange event if user enters the page with hash specified.




回答4:


You should bind an onclick event to anchor and specify return false; as a result. The return false; statement causes default click behaviour (jump) would not work. You can find more info here: How to disable anchor "jump" when loading a page?




回答5:


You need to pass the event on the function.

         var hash = window.location.hash;
         var link = $('a');
         //pass event here
         $('a').click(function(e) {
           e.preventDefault();
           hash = "#"+link.attr("href");
         });



回答6:


You can use match with ^ to detect starting with #

$("a:link").on("click", function(e){
    if($(this).attr("href").match("^#")) {
        e.preventDefault();
        //some other stuff you want to do with the hash, like smooth scroll to anchor
        $('html, body').animate({ scrollTop: $($(this).attr("href")).offset().top }, 'fast');
    }
});


来源:https://stackoverflow.com/questions/14185974/how-to-prevent-jump-on-an-anchor-click

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