我制作了这个自动url锚标记脚本,该脚本生成到该站点的链接,并跳转到该URL所来自的文章。 它工作正常,但是当我滚动浏览标题并更新网址时,它将捕捉到锚标记。所以我的问题是,是否有可能使它不捕捉而仅表现为正常滚动(测试代码段)
var url = "";
var anchor = "";
var element1 = "";
var element2 = "";
$(document).ready(function () {
url = window.location.href;
});
$(function () {
$(window).scroll(function () {
var findMiddleElement = (function (docElm) {
var viewportHeight = docElm.clientHeight,
elements = $('.subheading');
return function (e) {
var middleElement;
if (e && e.type == 'resize')
viewportHeight = docElm.clientHeight;
elements.each(function () {
var pos = this.getBoundingClientRect().top;
if (pos > viewportHeight / 2.5 && pos < viewportHeight / 1.5) {
middleElement = this;
return false;
}
});
element1 = middleElement;
if (element1 != element2) {
element2 = element1;
anchor = $(middleElement).text();
if (anchor != "") {
window.location.href = url + "#" + anchor;
}
}
}
})(document.documentElement);
$(window).on('scroll resize', findMiddleElement);
});
});
p{
padding: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class='subheading'><a name='test1'/>test1</p>
<p class='subheading'><a name='test2'/>test2</p>
<p class='subheading'><a name='test3'/>test3</p>
<p class='subheading'><a name='test4'/>test4</p>
<p class='subheading'><a name='test5'/>test5</p>
答案 0 :(得分:0)
类似于this
我对此进行了更改,以使运动更流畅:
if (anchor != "") {
$([document.documentElement, document.body]).animate({
scrollTop: $(middleElement).offset().top - 100
}, 1000);
}
-100
的偏移量很小,因为它一直滚动直到到达结尾为止。您可以找出确切的数字等。但这就是这个主意。