【问题标题】:How to prevent links to anchors in a child div from affecting main url?如何防止指向子 div 中锚点的链接影响主 url?
【发布时间】:2015-01-06 06:39:56
【问题描述】:

考虑以下 sn-p:

<div id="help"></div> 
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
    var loadPage = function (){
        $("#help").load("http://localhost:3000/manual.html");
    }
    onload=loadPage;
</script>

这存在于我的主页上:

http://localhost:3000/

上面的代码可以正常工作并加载我的手册页。但是,如果我在 manual.html 中单击这样的链接:

<a href='#introduction'>Introduction</a>

然后帮助 div 中的页面跳转到#introduction 部分,但是我的浏览器中的 url 更新为:

http://localhost:3000/#introduction

这是没有意义的,因为#introduction锚点只存在于manual.html中,如何防止#help div中的链接影响浏览器中的地址栏?

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    我已经有一个可以将#help 窗口滚动到标题的功能,当您单击父对象中的对象时,它会滚动到帮助窗口中的相关部分:

    var moveTo = function(destination){
        //position of the top of the help window - does not change.
        var helpWindow = $("#help").offset().top;                  
        //difference between current scroll position and target position.     
        var relativeDistance = $(destination).position().top - helpWindow; 
         //add the distance from current position to the top to get distance to target from top
        var absoluteDistance = relativeDistance+ $("#help").scrollTop();            
    
        $("#help").animate({
            scrollTop: absoluteDistance
        }, 1000);
    }
    

    使用 e.preventDefault() 我可以使用这个函数来做我想做的事。 对于其他走这条路的人来说,还有另外两件小事需要考虑。 首先,确保将 .click() 函数嵌套在页面加载的回调中,因为在加载页面之前超链接不存在。其次,您可能需要使用子选择器,例如 $('#help a').click() 以确保您只更改子内部链接的行为。

    $("#help").load("http://localhost:3000/manual.html", function(){
        $('#help a').click(function(e) {
            e.preventDefault();                     //suppress standard link functionality
            moveTo($(this).attr('href'));           //scroll to link instead.
        })        
    });
    

    【讨论】:

    • 这个答案和我的答案很相似。
    【解决方案2】:

    通过使用offsetpreventDefault

    $('a').click(function(e) {
         // Go to '#introduction'
         var targetId = $(this).attr('href');
         $('html, body').offset({ top: $(targetId).offset().top, left: 0 });
         // this prevent 'http://localhost:3000/#introduction'
         e.preventDefault();
    });
    

    this post

    【讨论】:

      【解决方案3】:

      试试这个

      $('a').click(function(e) {
          e.preventDefault();
          $("#help").load($(this).attr('href'));
      })
      

      【讨论】:

      • 这没有按预期工作,它试图将父级加载到子级中,但是感谢您指出 e.preventDefault(),一旦我知道如何取消默认值。
      猜你喜欢
      • 2023-03-27
      • 1970-01-01
      • 2022-01-26
      • 2021-01-10
      • 1970-01-01
      • 2017-04-03
      • 2010-11-27
      • 1970-01-01
      相关资源
      最近更新 更多