我在浏览器顶部有一个静态菜单,当有人点击链接时,菜单位于文本上方。
我这样做了,但scrollTop
不起作用:
jQuery(document).ready(function () {
$('a[href^="#"]').click(function()
{
var sHref = this.href.split("#");
$("#"+sHref[1]).scrollTop($("#"+sHref[1]).scrollTop() + 100); // <- does not work
});
});
答案 0 :(得分:7)
您不需要拆分href
属性,因为它已包含#
(您在选择器中检查)。
$(function() {
// Desired offset, in pixels
var offset = 100;
// Desired time to scroll, in milliseconds
var scrollTime = 500;
$('a[href^="#"]').click(function() {
// Need both `html` and `body` for full browser support
$("html, body").animate({
scrollTop: $( $(this).attr("href") ).offset().top + offset
}, scrollTime);
// Prevent the jump/flash
return false;
});
});
此外,为了使编辑更容易,您可以将偏移量从100
更改为$('menu_element').height()
。如果您更改了菜单,它将无需编辑JS即可使用。