我已经设置了一个具有平滑滚动功能的单页网站,该网站在平滑滚动后会从 URL 中删除 anchor 链接。这是我正在使用的 jQuery:
$(function() {
$('a.page-scroll').on('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top - 60
}, 1000, 'easeInOutExpo');
event.preventDefault();
});
});
一切都很好,直到我添加其他页面。我无法在像 <a class="page-scroll" href="../#contact">Contact</a>
这样的链接之后删除 anchor 链接。在另一个外部页面上。
我在 SO 上进行了大量搜索,但找不到有效的解决方案。
如果链接来自外部页面,我并不完全关心平滑滚动。我最需要的是导航/滚动到主页的 id 部分(带有偏移量以适应固定导航),并在链接来自外部页面(来 self 网站上的其他页面)时从浏览器 URL 窗口中删除 anchor 链接,或来自其他网站)。
我也尝试过这个,但它同样只适用于同一页面上的 id 的内部链接:
<script>
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - 60
}, 1000);
return false;
}
}
});
});
</script>
我也尝试过,但没有成功:
<script type="text/javascript">
(function($) {
$(document).ready(function() {
var url=document.URL.split("#");
var ancher=url[1];
$('html, body').animate({
'scrollTop': $('#'+ancher).offset().top - 60
}, 5000);
});
})(jQuery);
</script>
任何除夕夜的帮助将不胜感激,这样我就可以完成这个项目了!
最佳答案
我可能不明白问题的严重程度,但我相信您正在尝试做到这一点,以便 href 不会在想要滚动的页面上触发,但会在链接到其他页面的页面上触发,并且不是页面本身内的部分。也许这样的东西适合你:
$(function() {
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
if ($anchor[0].href[0] === '#') {
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top - 60
}, 1000, 'easeInOutExpo');
event.preventDefault();
return false;
} else {
return true;
}
});
});
它的作用是查看 href 中的前导字符是 #,这意味着它是指向其自身某个部分的链接。
让我知道这是否有帮助和/或我是否走在正确的道路上。
ps:我将 .bind 留在那里,因为我不知道您使用的是哪个版本的 jQuery,但较新的语法是使用 .on
新年快乐
只是稍微添加一些内容,以便主页的深层链接转到适当的部分,但没有哈希标签:
您可以从 window.location 中删除该“hash”变量,但如果您尝试完全删除主题标签,则会导致浏览器刷新。这也会导致观看者失去位置(从而消除深层链接的目的)。
要更改哈希标签值(保留 #):
window.location.hash = ''; // clears the hash tag
要删除井号标签及其值(清除 # 及其后面的所有内容):
window.location.href = window.location.href.substr(0, window.location.href.indexOf('#')); // this causes a browser refresh
如果它不完全明显,您可以在页面加载时运行它
$(document).ready(function() {
if (typeof(window.location.hash) !== 'undefined' && window.location.hash.length > 0) {
window.location.hash = ''; // will clear the hash anytime someone arrives with a hash tag
}
});
关于javascript - 滚动后删除 anchor 链接 - 也适用于其他页面的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34549793/