Javascript 在不更改url的情况下转到锚定
加载页面时,我希望它在不更改url的情况下转到Javascript 在不更改url的情况下转到锚定,javascript,window,anchor,Javascript,Window,Anchor,加载页面时,我希望它在不更改url的情况下转到#content 我想我可以用 window.location.hash = "content"; window.location.replace("#content", ""); 但是#内容仍然存在于url上 有更好的方法吗 编辑: 也试过 window.location.hash = "content"; window.location.replace(window.location.toString().replace("#content"
#content
我想我可以用
window.location.hash = "content";
window.location.replace("#content", "");
但是#内容仍然存在于url上
有更好的方法吗
编辑:
也试过
window.location.hash = "content";
window.location.replace(window.location.toString().replace("#content", ""));
但这会将浏览器发送到一个循环中。您可以找到具有该id的锚点的垂直位置,然后滚动到该位置。这将通过一个漂亮的动画完成:
<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>
单击并滚动到此div,而不更改url!
$('a')。在('click',函数(e)上{
//防止默认锚点单击行为
e、 预防默认值();
//存储散列
var hash=this.hash;
if($(散列).length){
$('html,body')。设置动画({
scrollTop:$(散列).offset().top
},300,函数(){
//如果你想做点有趣的事!
});
}
});
在不更改url的情况下,转到或滚动到锚定指定的div id
函数scrollSmoothTo(elementId){
var element=document.getElementById(elementId);
element.ScrollingToView({
块:“开始”,
行为:“平滑”
});
}
#userdiv{
利润上限:200px;
宽度:200px;
高度:400px;
边框:1px纯红;
}
a{
颜色:#337ab7;
光标:指针;
}
a:悬停{
文字装饰:下划线;
}
滚动到userdiv
这是一个随机文本
这是一个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>
)
};
const-Anchor:React.FC=()=>{
常量smoothScrollTo=e=>{
e、 预防默认值();
常量元素=document.getElementById('search');
element.ScrollingToView({
块:“开始”,
行为:“平滑”//平滑滚动
})
};
返回(
带我到这里!
)
};
现在,在这里使用REF可能是一个最佳实践,但这正是我所需要的!我相信还可以做其他的改进
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>
)
};