我不知道如何使 html 页面滚动到作为 url 一部分的特定字符串。
例如:如果假设用户给
html 页面包含很多 utc 时间值,基于用户在 url 中给定的 utc 值,页面应该滚动到用户在 url 中给出的那个 utc。
你能否建议如何在 html、javascript 等中执行此操作?
试试下面的代码:
var vars = [],
hash = '';
var hashes = window.location.href;
var decodedurl = decodeURIComponent(hashes);
var newurl = decodedurl.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < newurl.length; i++) {
hash = newurl[i].split('=');
console.log(hash);
vars[hash[0]] = hash[1];
}
setTimeout(function() {
if (vars['utc'] !== undefined && vars['utc'] == '1234567890 ') {
if (jQuery(window).width() >= 768) {
jQuery('html, body').animate({
scrollTop: jQuery('#utc_1234567890').offset().top - 210
}, 1500, 'swing');
} else {
jQuery('html, body').animate({
scrollTop: jQuery('#utc_1234567890').offset().top - 30
}, 1500, 'swing');
}
}
}, 3000);
将代码中的 utc_1234567890 替换为您要滚动到的 div 元素 ID,并将 1234567890 替换为 URL 中相应的 utc 值
基本上,只要您的浏览器包含在 url 中,您的浏览器就会自动跳转到锚链接。即 ?utc=7 在调用链接时自动跳转到 DOM 中设置锚点的位置。所以到地方
<div id="7">Hello World</div>
。如果您在 spa 应用程序中操作 url,浏览器当然可能不会立即跳转到该位置。在这里,您可以通过 js location api 触发它,或者您只需触发页面重新加载 ;-)(最简单的方法)。
这里有一个关于锚点的简短例子。
const navLinks = document.querySelectorAll('a');
navLinks.forEach(a => {
a.addEventListener('click', e => {
const tgt = e.target.getAttribute('href')
alert("jump to:" + tgt)
})
});
.page {
height: 100vh;
}
ul {
position: fixed;
background: green;
}
section {
border-bottom: 3px solid red;
height: 50%;
background-color: yellow;
margin-bottom: 10px;
}
<div class="page">
<ul>
<l><a href="#1">1</a></li>
<l><a href="#2">2</a></li>
<l><a href="#3">3</a></li>
<l><a href="#4">4</a></li>
</ul>
<section id="1">1</section>
<section id="2">2</section>
<section id="3">3</section>
<section id="4">4</section>
</div>
URL searchParams
和scrollIntoView()
方法。?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>