问题
Hello so I am working on a vertical scrolling site where fixed central image (the main character) hide and show depending on where the user is on the page using .scrolltop. The only problem I have is that when the page loads the first time, every single central image loads at once and is displayed. Once you begin scrolling it works correctly from the point on, it seems to only happen when the page is first loaded. What am I writing wrong in my script? I think it has to do with the .hide function not activating until the user scrolls, but I dont know how to write it differently.
Thank you.
Here's the site so you can see what I'm talking about:
http://pixel.csueastbay.edu/3870/corzine/project1/index.html
And here's a sample of the js:
<script>
$(window).scroll(function() {
if ($(this).scrollTop() > 290) {
$(".fallingman").hide();
}
if ($(this).scrollTop() < 290) {
$(".fallingman").show();
}
});
$(window).scroll(function() {
if ($(this).scrollTop() < 290) {
$(".fallingman2").hide();
}
if ($(this).scrollTop() > 290) {
$(".fallingman2").show();
}
if ($(this).scrollTop() > 1200) {
$(".fallingman2").hide();
}
});
</script>
回答1:
Put what you want into a function. Then call it unconditionally when the page loads, and also in the scroll handler.
function checkScroll() {
var pos = $(window).scrollTop();
if (pos > 290) {
$(".fallingman").hide();
$(".fallingman2").show();
}
if (pos < 290) {
$(".fallingman").show();
$(".fallingman2").hide();
}
if (pos > 1200) {
$(".fallingman2").show();
}
)
$(function() {
checkScroll();
$(window).scroll(checkScroll);
});
来源:https://stackoverflow.com/questions/16621731/hide-and-show-displaying-all-elements-and-not-functioning-properly-until-user