[英]How to scroll page down after anchor navigation?
I have added top menu as a div with position: fixed. 我添加了顶级菜单作为div位置:固定。 It's placed in the top of the page, so it covers part of the content.
它位于页面顶部,因此它涵盖了部分内容。 I moved the layout down, so generally it's ok, BUT if user clicks any anchor link, the page scrolled to where the anchor is on top.
我将布局向下移动,所以通常没关系,但是如果用户点击任何锚链接,页面会滚动到锚点位于顶部的位置。 But it's covered by the top menu.
但顶级菜单涵盖了它。 Is there a way to catch anchor event and process it with javascript (and jQuery if necessary)?
有没有办法捕获锚事件并使用javascript(如有必要,jQuery)处理它?
You can use something like this: 你可以使用这样的东西:
$('a').click(function(){
$('html').scrollTop($($(this).attr('href')).position().top + menu_height_offset)
})
To get the anchor position 获得锚定位置
$($(this).attr('href')).position().top
To make the offset related to the fixed menu 使偏移量与固定菜单相关
menu_height_offset
To make move the scroll 要移动滚动
$('html').scrollTop()
http://api.jquery.com/scrollTop/ http://api.jquery.com/scrollTop/
http://api.jquery.com/position/ http://api.jquery.com/position/
You need to calculate the offset of the element and sroll to the offset of element - height of the navigationbar
- position: 您需要计算元素的偏移量并滚动到
offset of element - height of the navigationbar
的offset of element - height of the navigationbar
栏的offset of element - height of the navigationbar
- 位置:
$("a").on("click",function(){
// height of the navigation bar
var height= $("#nav").outerHeight();
// position of the referenced dom-element
var pos = $($(this).attr("href")).position().top;
// scroll to the element
$("body").scrollTop(pos - height);
// suppress default
return false;
})
/* START --- scroll till anchor */
(function($) {
$.fn.goTo = function() {
var top_menu_height=$('#div_menu_header').height() + 5 ;
//alert ( 'top_menu_height is:' + top_menu_height );
$('html, body').animate({
scrollTop: (-1)*top_menu_height + $(this).offset().top + 'px'
}, 500);
return this; // for chaining...
}
})(jQuery);
$(document).ready(function(){
var url = document.URL, idx = url.indexOf("#") ;
var hash = idx != -1 ? url.substring(idx+1) : "";
$(window).load(function(){
// Remove the # from the hash, as different browsers may or may not include it
var anchor_to_scroll_to = location.hash.replace('#','');
if ( anchor_to_scroll_to != '' ) {
anchor_to_scroll_to = '#' + anchor_to_scroll_to ;
$(anchor_to_scroll_to).goTo();
}
});
});
/* STOP --- scroll till anchror */
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.