Fade a background in when you mouseover a box

蓝咒 提交于 2019-12-14 03:58:08

问题


I've asked this guestion before. But now I'll try to be a bit more specific.

I've trying to make a background fade in when you mouse over a box. I've tried 2 different options.

Option 1: Box1 is the box it mousesover, and hover1 is the new background that comes in. This actually works pretty well. However, it loads the acript, meaning, that if i just go crazy with my mouse over the box, the fadeing will continue endless, even when my mouse is standing still. Is there a way you can stop it? Content is a text that changes in a contentbox when I mouseover. This worksfine.

$("#box1").mouseover(function(){
    $("#background").switchClass("nohover", "hover1", 500);
    $("#content").html(box1);

});

$("#box1").mouseout(function(){
    $("#background").switchClass("hover1", "nohover", 150);
    $("#content").html(content);

});

Option 2: Here i add the class hover2 and asks it to fadeín and fadeout. But this doesn't work at all. Somtimes it even removes everything on the side when i take the mouseout of the box.

$("#box2").mouseover(function(){
    $("#background").addClass("hover2").fadeIn("slow") 
    $("#content").html(box3);
});

$("#box2").mouseout(function(){
    $("#background").removeClass("hover2").fadeOut("slow")
    $("#content").html(content);
});

I Use jquery ui. I really hope someone can help me!


回答1:


You can also try to make small changes in the markup/CSS.

HTML:

<div id="box">
    <div id="background"></div>
    <div id="content"></div>
</div>

CSS:

#box {
    position: relative;
    /* ... */
}
#background {
    position: absolute;
    display: none;
    top: 0;
    left: 0;
    width: inherit;
    height: inherit;
    background-image: url(...);
    z-index: -1;
}​

JavaScript:

$("#box").hover(function() {
    $("#background").fadeIn();
}, function() {
    $("#background").stop().fadeOut();
});​

DEMO: http://jsfiddle.net/bRfMy/




回答2:


Try add a variable to control the execution of the effect only when that variable has a certain value. And modify its value when the effect was executwed.

Something like this:

var goeft = 0;
$("#box1").mouseover(function(){
  if(goeft == 0) {
    $("#background").switchClass("nohover", "hover1", 500);
    $("#content").html(box1);
    goeft = 1;
  }
});

$("#box1").mouseout(function(){
    $("#background").switchClass("hover1", "nohover", 150);
    $("#content").html(content);
    // sets its value back to 0 if you want the next mouseover execute the effect again
    goeft = 0;
});


来源:https://stackoverflow.com/questions/10533130/fade-a-background-in-when-you-mouseover-a-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!