开发者

Can't see problem in JS

开发者 https://www.devze.com 2023-01-10 05:20 出处:网络
I want that when mouse is over an image, an event should be triggered ONCE, and it should be triggered again only after mouse is out of that image and back again, and also at least 2 seconds passed.

I want that when mouse is over an image, an event should be triggered ONCE, and it should be triggered again only after mouse is out of that image and back again, and also at least 2 seconds passed.

If I leave my mouse over the image,it gets called like every milisecond,and by the logic of my function once you hover on the variable 'canhover' becomes 0 until you move mouse out

This code seems to have a bug and I cant see it. I need a new pair of eyes, but the algorithm is kinda logical

Working code :

<script type="text/javascript">
var timeok = 1;
function redotimeok() {
    timeok = 1;
}
//
function onmenter()
{
if (timeok == 1) 
    {
  enter();
  timeok = 0;
    }
}
//
function 开发者_运维知识库onmleave()
{
  setTimeout(redotimeok, 2000);
  leave();
}
//

$('#cashrefresh').hover(onmenter,onmleave);

function enter(){
  $("#showname").load('./includes/do_name.inc.php');
  $("#cashrefresh").attr("src","images/reficonani.gif");
}

function leave(){
  $("#cashrefresh").attr("src","images/reficon.png");
}
</script>


I don't know if this will solve your entire problem (since we don't have a detailed description of what it is), but instead of:

$('#cashrefresh').hover(onmenter(),onmleave());

try:

$('#cashrefresh').hover(onmenter,onmleave);

And the same thing here:

setTimeout(redotimeok, 2000); // just the function name

Also, I don't see where you ever set timeok to zero. Do you mean to set timeok = 0 in onmenter()?


There are two methods in jquery for your problem:

.mouseenter() and .mouseleave()

Check out the demos there.

EDIT:

I thought hover was for mouseover and mouseout, sorry for confusion.

I checked your code again. And it seems that you're changing the image when mouse gets over the image, which forces browser to load the new image and the old image disappears for a very little while till the new one appears and i think this must be triggering both handlers continuosly and you're getting this behaviour.

Try not to change the source of the image, comment out that line and instead console.log("some message") there and see if the message is repeated as much as .load() was fired before.

Hope this helps.


Try changing onmleave function as follows:

   function onmleave()
    {
      setTimeout(redotimeok, 2000);
      leave();
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消