gpt4 book ai didi

javascript - 更改浏览器网址

转载 作者:行者123 更新时间:2023-11-29 15:12:14 25 4
gpt4 key购买 nike

你可以在上面看到我的演示代码

https://codepen.io/Nyarl/pen/EORXMe

$(window).on('load resize scroll', function() {
var activeFound = false;
$('article').each(function() {
if (!activeFound) {
if ($(this).is( ':in-viewport( 5 )')) {
$("article.current-new").removeClass("current-new");
$(this).addClass('current-new');
var url = $(this).data('url');
var title = $(this).data('page-title');
document.title = title;
history.pushState('data to be passed', title, url);
console.log(url);
activeFound = true;
}
}

});
});
article {
max-width:500px;
min-height:500px
}
article.current-new {
background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/is-in-viewport/3.0.4/isInViewport.min.js"></script>
<article data-url="https://stackoverflow/1" data-title="test">
<p>
<span>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Sapiente aliquam suscipit dolore non consequatur saepe provident vel molestias sequi, accusamus nemo consequuntur nisi ducimus aperiam illum cum expedita cumque tempora?</span>

</p>
</article>

我正在为我的博客开发无限滚动功能。我可以根据具有 .current new 类的元素更改元设置。

问题是,当我尝试更改 url 时,我的代码做了不止一次。因此,用户必须多次点击浏览器的上一个按钮才能访问其他帖子。

我通过 ajax 调用调用这些文章元素。

编辑:未指定脚本源:

最佳答案

您可以使用以下方法防止 pushState 将 url 多次添加到历史记录中:

if(!history.state || history.state.url != '/yourUrl'){
// then push state
}

通过 history.state 我们将检查是否设置了历史记录,如果是,我们需要确保此状态不等于 pushState url....

注意:pushState大部分是这样的:

history.pushState({ url: "/yourUrl" }, title, url);

关于javascript - 更改浏览器网址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53473012/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com