[英]Go to anchor without changing url
在加載頁面時,我希望它在不更改 url 的情況下轉到#content
。
我以為我可以使用
window.location.hash = "content";
window.location.replace("#content", "");
但#content
仍然存在於 url 上。
有什么更好的方法嗎?
編輯:
也試過
window.location.hash = "content";
window.location.replace(window.location.toString().replace("#content", ""));
但這會使瀏覽器進入循環。
您可以找到具有該 id 的錨點的垂直位置,然后滾動到該位置。
轉到或滾動以錨定指定的 div id 而不更改 url
function scrollSmoothTo(elementId) {
var element = document.getElementById(elementId);
element.scrollIntoView({
block: 'start',
behavior: 'smooth'
});
}
#userdiv {
margin-top: 200px;
width: 200px;
height: 400px;
border: 1px solid red;
}
a {
color: #337ab7;
cursor: pointer;
}
a:hover {
text-decoration: underline;
}
<a onclick="scrollSmoothTo('userdiv')">
Scroll to userdiv
</a>
<div id="userdiv">
Lorem ipsum this is a random text
</div>
這是一個 10 年前的問題,但我在使用 Nextjs 時遇到了這個問題,並希望在不影響 url 的情況下順利導航到較低的元素...... Nextjs,Typescript。
const Anchor: React.FC = () => {
const smoothScrollTo = e => {
e.preventDefault();
const element = document.getElementById('search');
element.scrollIntoView({
block: 'start',
behavior: 'smooth' // smooth scroll
})
};
return (
<div>
<a
href=""
onClick={smoothScrollTo}>
Let's go!
</a>
<div id = "search">Take me here!</div>
</div>
)
};
現在,在這里使用 refs 可能是最佳實踐,但這正是我所需要的! 我相信也可以進行其他改進!
這將通過一個漂亮的動畫來實現:
<a href="#link">Click to scroll</a>
<div id="link" style="margin-top: 1000px; height: 300px; background-color: blue; margin-bottom: 1000px">
Click and scroll to this div without changing url!
</div>
<script>
$('a').on('click', function(e) {
// prevent default anchor click behavior
e.preventDefault();
// store hash
var hash = this.hash;
if ($(hash).length) {
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 300, function() {
// Do something fun if you want!
});
}
});
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.