【问题标题】:Fade a background in when you mouseover a box将鼠标悬停在框上时淡入背景
【发布时间】:2012-05-10 11:33:36
【问题描述】:

我以前问过这个问题。但现在我会尝试更具体一点。

当您将鼠标悬停在框上时,我试图让背景淡入。我尝试了 2 种不同的选择。

选项 1: Box1 是鼠标悬停的盒子,hover1 是进来的新背景。这实际上工作得很好。但是,它会加载 acript,这意味着,如果我只是将鼠标悬停在盒子上而发疯,即使我的鼠标静止不动,褪色也会无休止地继续下去。有没有办法阻止它? 内容是鼠标悬停时在内容框中更改的文本。这工作正常。

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

});

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

});

选项 2: 在这里,我添加了 hover2 类并要求它淡入淡出。但这根本行不通。有时,当我将鼠标从盒子中取出时,它甚至会删除侧面的所有东西。

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

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

我使用 jquery ui。 我真的希望有人能帮助我!

【问题讨论】:

  • switchclass 是插件吗?听起来您需要在调用animate() 之前添加stop(),假设您可以修改源代码。
  • 是的,SWichClass 是一个来自 jquery ui 的插件。

标签: javascript jquery jquery-ui mouseover fade


【解决方案1】:

您也可以尝试在标记/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();
});​

演示: http://jsfiddle.net/bRfMy/

【讨论】:

  • 动画不透明度比淡入/淡出效果更好:jsfiddle.net/bRfMy/1
  • @Codemonkey 如果他们做同样的事情怎么办?
  • 他们没有。 fadeIn 和 fadeOut 还控制显示属性。只需尝试使用您的解决方案快速移入和移出鼠标,然后试试我的
【解决方案2】:

尝试添加一个变量来控制效果的执行,只有当该变量具有一定的值时。并在执行效果时修改其值。

类似这样的:

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;
});

【讨论】:

  • 非常感谢您的回答。但是,如果我多次将鼠标悬停在非常快的位置上,这仍然不会停止动画的运行。
猜你喜欢
  • 2011-01-25
  • 2011-07-05
  • 1970-01-01
  • 2013-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多