我不知道如何使html页面滚动到特定的字符串是url的一部分.
例如:假设用户给出
Html页面包含许多UTC时间值,基于用户在URL中给定的UTC值,页面应该滚动到用户在URL中给定的UTC.
你能建议一下如何用html、javascript等来做这件事吗?
我不知道如何使html页面滚动到特定的字符串是url的一部分.
例如:假设用户给出
Html页面包含许多UTC时间值,基于用户在URL中给定的UTC值,页面应该滚动到用户在URL中给定的UTC.
你能建议一下如何用html、javascript等来做这件事吗?
Use URL searchParams
and scrollIntoView()
method.
Working example on codepen.
In the example below, there will be scrolling to the block if the url contains ?utc=123
:
;(() => {
const params = ( new URL(location.href) ).searchParams;
const id = params.get('utc');
const block = document.getElementById(`utc-${id}`);
if (block) {
setTimeout(() => block.scrollIntoView({ behavior: 'smooth' }), 20)
}
})();
/* for testing */
#utc-123 {
margin: 100vh 0;
}
<div id="utc-123">utc-123</div>