使用jquery/javascript在滚动时更改url
我想在不使用滚动条的情况下更改url。这是我的代码:-使用jquery/javascript在滚动时更改url,javascript,jquery,html,Javascript,Jquery,Html,我想在不使用滚动条的情况下更改url。这是我的代码:- <a class = "section" href = "#first" > First paragraph < /a> < p > < /p> < a class = "section" href = "#second" > Second paragraph < /a> < p > < /p> < a class = "s
<a class = "section"
href = "#first" > First paragraph < /a> < p > < /p> < a class = "section"
href = "#second" > Second paragraph < /a> < p > < /p> < a class = "section"
href = "#third" > Third paragraph < /a> < p > < /p> < a class = "section"
href = "#fourth" > Fourth paragraph < /a>
function isScrolledIntoView(elem) {
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
$(window).scroll(function(e) {
var anchors = $('.section');
for (var i = 0; i < anchors.length; ++i) {
if (isScrolledIntoView(anchors[i])) {
var href = $(anchors[i]).attr('href');
location.hash = href.slice(href.indexOf('#') + 1);
break;
}
}
});
$(function() {
var hash = location.hash;
if (hash) {
// Scroll to the element with the given hash.
var anchors = $('.section');
for (var i = 0; i < anchors.length; ++i) {
if ($(anchors[i]).attr('href') === hash) {
$(window).scrollTop($(anchors[i]).offset().top);
break;
}
}
}
});
但我想这样表现:
file:///C:/Users/jony/Desktop/demo.html/third
如果要创建新的历史记录条目,即用户可以单击“上一步”按钮返回,请使用
window.history.pushState(state, title, newURL);
否则,请使用
window.history.replaceState(state, title, newURL);
如果不知道如何处理状态和标题,可以传递null或空字符串
如果没有你,这是不可能的,你可以拥有/第三,但不仅仅是/third@mohamedrias如果您选中此url,这正是我想要的功能。您为什么要删除哈希?esppushState@YuryTarabanko我查看了许多关于pushstate和history.js的帖子和文章,但它们都没有什么文档,我不知道如何将这些应用到我的代码中。
window.history.replaceState(state, title, newURL);