问题
Demo here:
http://jsfiddle.net/auMd5/
I want the blue menu bar to stick to the top of the page when you scroll past it, and then to snap back to its original position when you scroll back up over it. In every other browser I've tested, having jQuery conditionally switch the menu's position
from relative
to fixed
works. But it doesn't work in IE7.
To test, I've tried removing all the JavaScript and setting the position
to fixed
in the CSS. This looks as it should in IE7.
Also to test, I've had the condition if ($('table#menu').position().top + 10 <= $(window).scrollTop())
trigger an alert. It works, meaning that IE7 recognizes the event.
So the CSS I want works statically, and the JavaScript condition is working. Any ideas on what the issue could be?
回答1:
It seems that if you .remove()
the DOM element, change it's CSS, and then add it back to the DOM it works as expected in IE 7:
$(function() {
//cache all the objects we will need and get the initial top offset for the #menu
var $window = $(window),
$menu = $('#menu'),
menuTop = $menu.offset().top,
$midWrap = $('#mid-wrap');
$window.scroll(function() {
//cache a copy of the #menu object and get it's CSS position property
var $tmp = $menu,
position = $tmp.css('position'),
windowTop = $window.scrollTop();
$menu.remove();
//if the position is not already set to fixed and the #menu element is above the fold
if (position != 'fixed' && menuTop <= windowTop) {
//remove the current #menu element from the DOM
$menu.remove();
//set the position property of the new #menu element
$tmp.css('position', 'fixed');
//re-insert the #menu item into the dom
$midWrap.prepend($tmp);
$menu = $tmp;
//if the position is not already set to relative and the #menu element's offset is greater than how far the user has scrolled down
} else if (position != 'relative' && menuTop > windowTop) {
//remove the current #menu element from the DOM
$menu.remove();
//set the position property of the new #menu element
$tmp.css('position', 'relative');
//re-insert the #menu item into the dom
$midWrap.prepend($tmp);
$menu = $tmp;
}
});
});
Here is a demo: http://jsfiddle.net/auMd5/5/
来源:https://stackoverflow.com/questions/8698990/ie7-cant-get-menu-to-stick-to-top-of-page