防止滚动更改哈希值

Vin*_*hua 2 javascript anchor scroll hyperlink

对不起下面丑陋的布局示例... http://www.wthdesign.net/test/test2.html

我设法将我的id名称附加到网址:

function generateUrl(el)
{
    var currentId = $(el).attr('id');
    document.location.hash = currentId;
}
Run Code Online (Sandbox Code Playgroud)

并添加:

<a id="abc2" onClick="generateUrl(this)" >this is an anchor btn</a>
Run Code Online (Sandbox Code Playgroud)

但最终会产生与以下相同的效果:

<a id="abc2" href="#abc2" >this is an anchor btn</a>
Run Code Online (Sandbox Code Playgroud)

一切都很好,但我只是不想在我点击链接时滚动我应该怎么做?提前谢谢了.

m59*_*m59 10

如果不需要id,则只需href="#some-value更改窗口位置而不滚动页面.如果确实需要id文档(在本例中为a标签),则位置更改将导致滚动.您可以通过history在现代浏览器中使用该对象或通过在链接单击上存储滚动位置,然后使用该hashchange事件重置它来解决此问题.

我会将这个标记用于两种解决方案:

样本标记:

<div class="filler"></div>
<a id="abc1" href="#abc1" class="my-class">this is an anchor btn</a>
<div class="filler"></div>
<a id="abc2" href="#abc2" class="my-class">this is an anchor btn</a>
<div class="filler"></div>
<a id="abc3" href="#abc3" class="my-class">this is an anchor btn</a>
<div class="filler"></div>
Run Code Online (Sandbox Code Playgroud)

history.replaceState或history.pushState

现场演示(点击).

//get element referneces
var elems = document.getElementsByClassName('my-class');

//iterate over the references
for (var i=0; i<elems.length; ++i) {
  //add click function to each element
  elems[i].addEventListener('click', clickFunc);
}

//this will store the scroll position
var keepScroll = false;

//fires when a ".my-class" link is clicked
function clickFunc(e) {
  //prevent default behavior of the link
  e.preventDefault();
  //add hash
  history.replaceState({}, '', e.target.href);
}
Run Code Online (Sandbox Code Playgroud)

scrollTop和hashchange事件

现场演示(点击).

JavaScript的:

//get element referneces
var elems = document.getElementsByClassName('my-class');

//iterate over the references
for (var i=0; i<elems.length; ++i) {
  //add click function to each element
  elems[i].addEventListener('click', clickFunc);
}

//this will store the scroll position
var keepScroll = false;

//fires when a ".my-class" link is clicked
function clickFunc(e) {
  //if the location hash is already set to this link
  if (window.location.hash === '#'+e.target.id) {
    //do nothing
    e.preventDefault(); 
  }
  else {
    //the location will change - so store the scroll position
    keepScroll = document.body.scrollTop;
  }
}

window.addEventListener('hashchange', function(e) {
  //the location has has changed

  //if "keepScroll has been set
  if (keepScroll !== false) {
    //move scroll position to stored position
    document.body.scrollTop = keepScroll;
    //set "keepScroll" to false so that this behavior won't affect irrelevant links
    keepScroll = false;
  }
});
Run Code Online (Sandbox Code Playgroud)