滚动到最后用斜杠锚定
Scroll to anchor with slash at the end
我有一个网站,其中的部分有 # 并且菜单项应该滚动到它们。由于网站的设置,我的 URL 必须在末尾有 /(斜杠)。
例如网站。com/about/
所以锚点将是网站。com/about/#team/
当 URL 末尾有 / 时,滚动到锚点不起作用。我在网站上没有任何 jQuery,所以简单地跳转到该部分也不起作用。当我删除 / 它有效。
是否有 jQuery 可以用于此目的?我尝试了一堆 jQuery 但没有成功。
$(document).ready(function(){
// Add smooth scrolling to all links
$("a").on('click', function(event) {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
window.location.hash = hash;
});
});
});
正如您所说,您无法更改哈希模式,那么您必须执行逆向过程:在放置 $(hash).offset() 方法之前从 this.hash 中删除破折号
$(document).ready(function(){
$('a').click(function(event) {
// Store hash
event.preventDefault();
var hashWithoutDash = this.hash.replace("/",""); // remove dash from hash to make $(hashWithoutDash).offset() worked
$('html, body').animate({
scrollTop: $(hashWithoutDash).offset().top
}, 1000, function() {
window.location.hash = this.hash; // keep actual hash with dash
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<p id="team">This is a paragraph.</p>
<div style ="height:1000px"> please scroll down to see href link </div>
<a href="#team/"> team </a>
<button>Return the offset coordinates of the p element</button>
我有一个网站,其中的部分有 # 并且菜单项应该滚动到它们。由于网站的设置,我的 URL 必须在末尾有 /(斜杠)。
例如网站。com/about/
所以锚点将是网站。com/about/#team/
当 URL 末尾有 / 时,滚动到锚点不起作用。我在网站上没有任何 jQuery,所以简单地跳转到该部分也不起作用。当我删除 / 它有效。
是否有 jQuery 可以用于此目的?我尝试了一堆 jQuery 但没有成功。
$(document).ready(function(){
// Add smooth scrolling to all links
$("a").on('click', function(event) {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
window.location.hash = hash;
});
});
});
正如您所说,您无法更改哈希模式,那么您必须执行逆向过程:在放置 $(hash).offset() 方法之前从 this.hash 中删除破折号
$(document).ready(function(){
$('a').click(function(event) {
// Store hash
event.preventDefault();
var hashWithoutDash = this.hash.replace("/",""); // remove dash from hash to make $(hashWithoutDash).offset() worked
$('html, body').animate({
scrollTop: $(hashWithoutDash).offset().top
}, 1000, function() {
window.location.hash = this.hash; // keep actual hash with dash
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<p id="team">This is a paragraph.</p>
<div style ="height:1000px"> please scroll down to see href link </div>
<a href="#team/"> team </a>
<button>Return the offset coordinates of the p element</button>