Avoid window jump to top when clicking #-links

后端 未结 12 1117
礼貌的吻别
礼貌的吻别 2020-11-27 21:32

I\'ve got a page with some questions and answers, the answers are collapsed by default. When they click the question I expand the hidden answer-div. The problem is that when

相关标签:
12条回答
  • 2020-11-27 21:56

    Example with nice scrolling to answer content:

    $("#question_title").click(function(){
      var $answer=$("#answer");
      $answer.slideDown();
      $.scrollTo( $answer, 800 );
      return false;
    });
    

    I'm used jQuery scrollTo plugin.

    0 讨论(0)
  • 2020-11-27 22:01

    You can do it very simple: Just add ! in the end of your href:

    <a href="#!" id="myID">Myquestion</a>
    

    The alternative jQuery ways are:

    $("#myID").click(function(e) {
        e.preventDefault(); // one way 
        return false; // second way prevent default click action from happening
    });
    
    0 讨论(0)
  • 2020-11-27 22:01

    Actually, the easiest way to do this is to remove the href attribute from your anchor tag. As of HTML5, anchor tags don't need to include href attributes to be semantic.

    So

    <a id="myID">Myquestion</a>
    

    instead of

    <a href="#" id="myID">Myquestion</a>
    

    This works in IE8+, Chrome, and Firefox. Note that :link css styles won't apply to anchor tags that don't include href attributes.

    If you need the href attribute and/or IE7 compatibility, then

    $("#myID").click(function(e) {
    if(e.preventDefault)
        e.preventDefault();
    else
        e.stop();
    });
    

    is probably the best way to go.

    0 讨论(0)
  • 2020-11-27 22:02
    $('a').click( function() {
      if ($(this).attr("href") == window.location.hash) {
        event.preventDefault()
      }
    });
    
    0 讨论(0)
  • 2020-11-27 22:04
    $("#myID").click(function(e) {
        if(e.preventDefault)
            e.preventDefault();
        else
            e.stop();
    });
    

    e.preventDefault()alone did not work in older versions of IE.

    0 讨论(0)
  • 2020-11-27 22:06

    Don't use A tags for tasks that are not navigation-related. It is not semantic markup, and doesn't degrade gracefully. Use buttons instead.

    0 讨论(0)
提交回复
热议问题