问题
I need a sticky header on a mobile browser. I'm currently using this jquery script:
<script>
$(function(){
var stickyHeader = $('#persist-wrap').offset().top;
$(window).scroll(function(){
if( $(window).scrollTop() > stickyHeader ) {
$('#persist-wrap').addClass("sticky");
} else {
$('#persist-wrap').removeClass("sticky");
}
});
});
</script>
with this CSS code:
.sticky {
position: fixed;
top: 0;
}
The header has an id of persist-wrap. This works fine on a desktop browser but not at all on a mobile browser.
Any ideas?
回答1:
I've tweaked your example a little and it works for me on the Samsung Galaxy S2 running ICS and iPad 3 running iOS 6.01: (don't have any others to hand to test it on).
List of changes
- I cached all the objects that were used multiple times.
- Changed it so its a reusable function accepting a parameter of an object so it can be applied multiple times (this could be tweaked to accept multiple objects at once).
Here's the example:
$(function(){
createSticky(jQuery("#header"));
});
function createSticky(sticky) {
if (typeof sticky !== "undefined") {
var pos = sticky.offset().top,
win = jQuery(window);
win.on("scroll", function() {
win.scrollTop() >= pos ? sticky.addClass("fixed") : sticky.removeClass("fixed");
});
}
}
#header {
background: #666;
padding: 3px;
padding: 10px 20px;
color: #fff;
}
#header.fixed {
position: fixed;
top: 0;
width: 100%;
}
/* For aesthetics only */
body {
margin: 0;
height: 10000px;
font-family: Segoe, "Segoe UI", "DejaVu Sans", "Trebuchet MS", Verdana, sans-serif;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Some Text before the header</p>
<div id="header">
Home
</div>
来源:https://stackoverflow.com/questions/12573532/sticky-header-on-mobile-browser