首页 > 解决方案 > 当 URL 中存在哈希时,防止浏览器滚动到元素但将其保留在 URL 中

问题描述

我有一些按钮可以加载问题和答案(这是一个常见问题解答)。单击按钮时,我使用window.location.hash在 URL 中设置哈希来获取人们可以复制的 URL,因此稍后我可以自动打开一个带有问题的按钮,例如:website.nl/faq#category1

问题是当单击按钮并设置哈希时,浏览器会立即滚动到按钮,这不是我想要的。我怎样才能关闭它?

这是我目前的代码:

if(window.location.hash) {
    var hash = window.location.hash.substring(1); //Puts hash in variable, and removes the # character
    $('#' + hash).addClass('activeblok');
    } else {

}

const $blokje = $('.klantenblokje');
$blokje.on("click", function(e) {
    e.preventDefault();
    var id = $(this).attr('id');
    $blokje.not(this).removeClass('activeblok');
    $(this).addClass('activeblok');
        window.location.hash = id;
        // Ajax post which retrieves the questions
        $.ajax({
         type:'post',
         url:"includes/faqresult.php",
         data:{id: id},
         success:function(data){
             $( "#faqresult" ).show().empty().append( data );
         }
     });
});

还有我的 HTML:

<div class="col-md-2 col-6">
  <a href="#bezorgen" id="bezorgen" class="klantenblokje">
    <i class="icon-transport"></i>
    <span>Bezorgen</span>
  </a>
</div>
<div class="col-md-2 col-6">
  <a href="#bestellen" id="bestellen" class="klantenblokje">
    <i class="icon-cart"></i>
    <span>Bestellen</span>
  </a>
</div>
<div class="col-md-2 col-6">
  <a href="#betalen" id="betalen" class="klantenblokje">
    <i class="icon-euro"></i>
    <span>Betalen</span>
  </a>
</div>
<div class="col-md-2 col-6">
  <a href="#uploaden" id="uploaden" class="klantenblokje">
    <i class="icon-upload"></i>
    <span>Bestanden uploaden</span>
  </a>
</div>
<div class="col-md-2 col-6">
  <a href="#garantie-reparatie" id="garantie-reparatie" class="klantenblokje">
    <i class="icon-box"></i>
    <span>Garantie en reparatie</span>
  </a>
</div>
<div class="col-md-2 col-6">
  <a href="#account" id="account" class="klantenblokje">
    <i class="icon-user"></i>
    <span>Account</span>
  </a>
</div>

我从另一个问题尝试过这个但没有结果:

if (location.hash) {
  setTimeout(function() {

    window.scrollTo(0, 0);
  }, 1);
}

标签: javascripthtmljqueryurl

解决方案


您可以通过使用HTML5 History API及其pushStatereplaceState方法来做到这一点。

history.pushState(true, '', '#your-hash')

或者

history.replaceState(true, '', '#your-hash')

两者都会改变地址栏中显示的 URL,但不会跳转到页面中的元素,滚动位置将保持原样。

两者之间的区别在于,第一个将在浏览器历史记录中创建一个新条目,而第二个将覆盖当前条目 - 所以这将影响用户点击浏览器中的“后退”按钮时发生的情况. 如果您更改了五次哈希,但不希望用户必须单击六次后退按钮才能返回上一页,则使用replaceState.


推荐阅读