[英]A menu that stays on top with absolute position
jQuery jQuery的
$(document).ready(function() {
var offset = $(".menu").offset();
$(window).scroll(function () {
var scrollTop = $(window).scrollTop();
if (offset.top < scrollTop) {
$(".menu").css({
position: "fixed"
});
}
else {
$(".menu").css({
position: "absolute"
});
}
});
});
CSS CSS
.menu {
position: absolute;
top: 0px;
right: 0px;
}
As you imagine my menu always stays on top when scrolling down. 如您所想,向下滚动时,我的菜单始终位于顶部。 But there is a catch here.
但是这里有一个陷阱。 My menu is positioned absolutely because it is located inside a large relative container div.
我的菜单位于绝对位置,因为它位于较大的相对容器div中。 However if I wish for the menu to stay on top I have to change the positioning to fixed, which all works fine but menu now gets displaced outside of the large container div!
但是,如果希望菜单保留在最前面,则必须将位置更改为固定,这一切都很好,但是菜单现在已移至大容器div之外! Is there a way to position my menu to always stay on top but to retain its absolute value?
有没有一种方法可以使菜单始终位于顶部,但保持其绝对值呢? I really want that menu in one place, this means top:0 and right container border also 0!
我真的想将该菜单放在一个位置,这意味着top:0和右边的容器边界也为0!
Nothing moves outside of the central container and top is always 0. 什么都不会移出中央容器,并且top始终为0。
Fiddle link: http://jsfiddle.net/t6nue/2/ 小提琴链接: http : //jsfiddle.net/t6nue/2/
You need to remove comma: 您需要删除逗号:
if (offset.top < scrollTop) {
$(".menu").css({
position: "fixed"//, //here no need to use comma
});
I fixed the problem of jumping menu button like so: 我解决了跳转菜单按钮的问题,如下所示:
jQuery jQuery的
$(document).ready(function() {
var offset = $(".menu").offset();
$(window).scroll(function () {
var scrollTop = $(window).scrollTop();
if (offset.top < scrollTop) {
$(".menu").css({
top: scrollTop - "8"
});
}
else {
$(".menu").css({
top: "0px"
});
}
});
});
Notice I declare top position with jQuery variable: top: scrollTop - "8"
注意,我用jQuery变量声明了最高位置:
top: scrollTop - "8"
Problem solved :) 问题解决了 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.