繁体   English   中英

单击锚链接时保持 URL 不受影响

[英]Keep URL unaffected when anchor link is clicked

我已经检查了这里的其他帖子,没有我正在寻找的结果。 我想点击

<a href="#about">About</a>
<div id="about">Content of this..</div>

您可以使用 javascript 和 jquery 执行您想要的操作,示例如下(请注意,这是使用旧版本的 jquery):

<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>

    <script type='text/javascript'>
    jQuery(document).ready(function($) {

        $(".scroll").click(function(event){
            event.preventDefault();
            $('html,body').animate({scrollTop:$(this.hash).offset().top}, 1200);
        });
    });
    </script>
</head>
<body>
    <a class="scroll" href="#codeword">Blue Words</a>
    <div id="codeword"></div>
</body>
</html>

我自己玩过这个,这里是我在这个主题上的学习总结。

这是基本的链接命令:

<A HREF="#codeword">Blue Words</A>

以下是您表示跳转将滚动页面的位置的方式:

<A NAME="codeword">

这是发生了什么

A HREF 命令与基本链接相同,只是链接是指向代码字而不是 URL。

请注意,代码字前面有一个# 符号。 您需要用它来表示它是一个内部链接。 如果没有 # 符号,浏览器会在以您的代码字命名的页面之外查找内容。

您的“代码字”可以是您想要的任何内容。 我尽量保持简短,并让它表示它要跳到什么地方。 您可以使用的字母数量可能有限制——但我还没有找到。

页面跳转的点遵循相同的一般格式,除了您将用单词 NAME 替换单词 HREF。

请注意 NAME 命令中没有 # 符号。

笔记! 您放置 NAME 目标的位置将出现在屏幕浏览器的顶部。

希望能帮助到你。

window.location.hash = ""  

是我能找到的可能方式。

hash给出#旁边的字符串。

//不使用a,使用类

 $(document).ready(function(){
 $(".mouse").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
  if (this.hash !== "") {
  // Prevent default anchor click behavior
  event.preventDefault();
 // Store hash
  var hash = this.hash;
 // Using jQuery's animate() method to add smooth page scroll
  // The optional number (800) specifies the number of milliseconds it takes 
 to scroll to the specified area
  $('html, body').animate({
    scrollTop: $("#section").offset().top
  }, 800, function(){
   // Add hash (#) to URL when done scrolling (default click behavior)
    window.location.hash = "";
  });
} // End if  }); });

一种可能的解决方法是使用<button>而不是<a>

所以而不是......

<a href="#about">About</a>
<div id="about">Content of this..</div>

...你可以把它改成

<button href="#about">About</button>
<div id="about">Content of this..</div>

这样锚链接就不会影响 URL。

对我来说,只插入“return false;” 解决了这个问题。

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>   
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js" async></script>
<script>
jQuery(document).ready(function($) {
    $('a[href^=#]:not(a[href=#])').click(function() {
        $('html, body').animate({scrollTop: $(this.hash).offset().top}, 1300, 'easeInOutExpo');
        return false;
    });
});
</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM