0

How the current version of my code works:

When a user's mouse pointer hovers a Nav element the background image of the website fades to a smaller less opaque version. When the mouse leaves the nav Element it returns to the previous image.

The code for this looks like this:

$(document).ready(function(){
  $("li a").mouseenter(function(){
    $('.image').fadeTo(100, 0.5, function() {
    $(".image").css("background","url(images/backdrop_smaller.png)");
    });
  });
$("li a").mouseout(function(){
    $('.image').fadeTo(100, 1.0, function() {
    $(".image").css("background","url(images/backdrop_orig.png)");
  });
  });
}); 

The only problem with this is that if the user rapidly moves in between Nav elements the image rapidly shifts (which looks disorienting) and eventually lags behind the users command (due to the .fadeTo interval).

So as to prevent this I thought I would set up a console timer to print the time when the User leaves a nav element and enters another. Then create an if function to dictate whether or not the first mouseout transition plays to completion.

The timer looks like this:

$(document).ready(function(){
  $("li a").mouseout(function(){
    console.time("time")
});
});

  var FunctionEndTime = $(document).ready(function(){
  $("li a").mouseenter(function(){
    var end = console.timeEnd("time")
});
});

My problem lies in referencing this printed console time in the if function and then also preventing the fade triggered by .mouseout from playing to completion. For example, if the the time difference was less than the fade time (100ms) the fade would stop transitioning. This would leave the smaller less opaque background image and prevent disorienting image flicker and

Here is what my not working code looks like:

function TimeReset() {
  if (end < 25)
  {
    $(document).ready(function(){
  $("li a").mouseout(function(){
     $('.image').fadeTo(100, 0.5, function() {
    $(".image").css("background","url(images/backdrop_smaller.png)");
      });
  });
});
}

The code above obviously does not do what I would like and is referencing things incorrectly. I just am not sure how to do it properly.

The question is: am I thinking about this all incorrectly? or do I just not know how to implement the code to completion?

4

1 回答 1

0

To prevent blinking on rapid cursor moving you may consider using $.stop() before queuing new animation step. It should look like that:

$('.image').stop().fadeTo(100, 0.5, function() { ...

Note that $.stop() has two optional parameters that can be helpful.

于 2012-12-05T14:24:55.257 回答