问题
I know the title isn't the most descriptive and there are many more topics with similar questions like this, but I couldn't find any answers. In fact, I got this far thanks to you guys so, here's what I'm trying to do.
I have a DIV that I want to show when the page is scrolled to a certain position (trigger), marked by #othdiv. This DIV disappears when you scroll further down to the next position (trigger) marked as #othdiv2.
This feels like it's a very simple solution but I just can't figure it out. I have tried conditional if statements, duplicating codes, removing lines, new variables... sigh... please help.
$(document).ready(function() {
$("#dvid").hide(); //hide your div initially
var topOfOthDiv = $("#othdiv").offset().top;
var topOfOthDiv2 = $("#othdiv2").offset().top;
$(window).scroll(function() {
if($(window).scrollTop() > topOfOthDiv) { //scrolled past the other div?
$("#dvid").show(); //reached the desired point -- show div
}
else
if($(window).scrollTop() < topOfOthDiv) { //scrolled past the other div?
$("#dvid").hide(); //reached the desired point -- show div
}
});
});
Current code sample: http://jsfiddle.net/DnJ2z/124/
Bottom line: I'm trying to do something similar to this: http://mailchimp.com/2012/ (notice the titles [the app, support, operations, etc])
回答1:
Try using &&
as in: if (this and that){do something} else{don't}
Working Example
$(document).ready(function () {
var topOfOthDiv = $("#othdiv").offset().top;
var topOfOthDiv2 = $("#othdiv2").offset().top;
$(window).scroll(function () {
if ($(window).scrollTop() > topOfOthDiv && $(window).scrollTop() < topOfOthDiv2) {
$("#dvid").show();
} else {
$("#dvid").hide();
}
});
});
For a much better explanation of logical operators check out: Logical Operators MDN
回答2:
I was playing with your fiddle and manage to get it working. Check if it's what you want:
$(document).ready(function() {
$("#dvid").hide(); //hide your div initially
var topOfOthDiv = $("#othdiv").offset().top;
var topOfOthDiv2 = $("#othdiv2").offset().top;
$(window).scroll(function() {
if($(window).scrollTop() > topOfOthDiv && $(window).scrollTop() < topOfOthDiv2) { //scrolled past the other div?
$("#dvid").show(); //reached the desired point -- show div
}
else
if($(window).scrollTop() < topOfOthDiv || $(window).scrollTop() > topOfOthDiv2) { //scrolled past the other div?
$("#dvid").hide(); //reached the desired point -- show div
}
});
});
来源:https://stackoverflow.com/questions/16781742/show-hide-div-with-scroll