抱歉下面的丑陋布局示例...... http://www.wthdesign.net/test/test2.html
我设法将我的ID名称附加到网址:
function generateUrl(el)
{
var currentId = $(el).attr('id');
document.location.hash = currentId;
}
并添加:
<a id="abc2" onClick="generateUrl(this)" >this is an anchor btn</a>
但最终会产生与以下相同的效果:
<a id="abc2" href="#abc2" >this is an anchor btn</a>
一切都很好,但是当我点击链接时我只是不想滚动它 我该怎么办?非常感谢提前。
答案 0 :(得分:9)
如果不需要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>
<强> Live demo (click). 强>
//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);
}
<强> 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;
}
});
答案 1 :(得分:1)
我遇到的问题是,我使用平滑滚动行为,并且在单击锚链接时,Firefox 滚动位置会四处跳跃。所以这里堆栈溢出没有任何效果。如果有人对我最近的方法感兴趣:
这是一个例子:
document.addEventListener('DOMContentLoaded', () => {
// store scroll position
let scrollTop = document.documentElement.scrollTop
window.addEventListener('scroll', () => scrollTop = document.documentElement.scrollTop)
window.addEventListener('hashchange', () => {
// disable scrolling
document.body.style.overflow = 'hidden'
// set current scroll position
window.scroll(0, scrollTop)
// enable scrolling
setTimeout(() => {
document.body.style.overflow = 'auto'
}, 10)
}, false)
// trigger hashchange event on page load
window.dispatchEvent(new Event('hashchange'))
})