2

I have the following code, that changes the class of a div when you scroll down. The problem is if you scroll very fast (or if I put links to a div in my menu) the timeout function doesn't execute just the last condition but all of them as a sequence. What I want to do is if the condition changes while the function is within the timeout to skip the function and check for the next condition.

  $(document).scroll(function() {    
  var about = jQuery('#hh1').position().top;
  var portfolio = jQuery('#hh2').position().top;
  var services = jQuery('#hh3').position().top;
  var workingprocess = jQuery('#hh4').position().top;
  var clients = jQuery('#hh5').position().top;
  var blog = jQuery('#hh6').position().top;
  var contact = jQuery('#hh7').position().top;
  var scroll = $(this).scrollTop();
  if (scroll >= hh1-90 && scroll < hh3-90 || scroll >= hh5-90 && scroll < hh6-90)
  {setTimeout('$(".div").addClass("MyClass")',3440);}
  else 
  {
  setTimeout('$(".div").removeClass("MyClass")',3440);
  }
  });
4

2 回答 2

4

setTimeout(...) method takes a function to execute when the timeout occurs. You are not sending it a function.

setTimeout('$(".div").addClass("MyClass")',3440);

Change this to

setTimeout(function(){$(".div").addClass("MyClass")},3440);

and then -

You have to store the numerical timeout id returned by the setTimeout(...) method and use it to clear the timeout clearTimeout(...).

Save the timeout id like

timeoutID = setTimeout(function(){$(".div").addClass("MyClass")},3440);

and then use it to clear the timer.

clearTimeout(timeoutID);

You don't need to check if the timeout has occurred or not because if the timeout occurred, the function specified would have been called already and if it hasn't, you need to clear it. So, just clear the timeout when the condition changes.

于 2013-09-15T23:51:37.087 回答
0

Try this:

var addClass = function() {
    $(".div").addClass("MyClass");
}

var removeClass = function() {
    $(".div").removeClass("MyClass");
}

if (scroll >= hh1-90 && scroll < hh3-90 || scroll >= hh5-90 && scroll < hh6-90)
  {
      setTimeout( myClass,3440);
  }
  else 
  {
      setTimeout(removeClass,3440);
  }
于 2013-09-15T23:54:50.410 回答