CSS悬停使用jQuery淡出

时间:2010-07-06 09:14:41

标签: jquery css

我有一个简单的链接,当用户徘徊时会发生变化,所以我们会这样做:

a.mylink {
    background: url(..) top left no-repeat;
    width: 100px; height: 100px;
}

a.mylink:hover,
a.mylink.jqHover {
    background: url(..) top left no-repeat;
    color: red;
}

改变了我对我想要发生的事情的看法,基本上我想做到这一点,以便当用户悬停链接时它会执行:悬停的东西,但缓慢而不是立即。所以就像过渡效应一样。我已经把它变成了一个类,以便更容易处理悬停malarkey,所以我猜一个简单的添加类并删除类但是使用某种淡入淡出计时器?

我正在努力做到这一点:

$('a.mylink').hover(
            function () {
                $(this).addClass('.jqHover');
            },
            function () {
                $(this).removeClass('.jqHover');
            }
        );

但我希望它能在两个班级之间淡出!

///////////////////////编辑:

这是我目前的代码 - >

$("ul.BrightLozenges li a").hover(

        function() {
            $(this).switchClass('Normal','Special',200,'easeOutBounce');
        }, 
        function() {    
            $(this).switchClass('Special','Normal',200,'easeOutBounce');
        });

哪种方法很好,但是我想让它淡入淡出,尝试使用'淡入淡出'作为转换,但它不起作用?

3 个答案:

答案 0 :(得分:1)

如果符合您的需要,您可以创建精灵图像并为其背景位置设置动画。

看一下这篇文章http://snook.ca/archives/javascript/jquery-bg-image-animations/

除此之外,你必须淡出整个元素,添加一个具有新BG的类,并淡入元素。如果它发生得非常快(即200 / 300ms),那么转换应该非常好。

您可以尝试这样的事情:

$(document).ready(function() {
    $(".mylink").hover(function() {
        $(this).fadeOut(200).addClass("jqHover").fadeIn(300);
    },
        $(this).fadeOut(200).removeClass("jqHover").fadeIn(300);
    );
}

答案 1 :(得分:1)

使用switchClass中的jQuery UI方法。

$(elem).switchClass('currentClass', 'newClass', 500);

答案 2 :(得分:0)

使用:.hover()

以下示例也适用于我粘贴的链接页面。

<!DOCTYPE html>
<html>
<head>
  <style>
  ul { margin-left:20px; color:blue; }
  li { cursor:default; }
  span { color:red; }
</style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
 <ul>
    <li>Milk</li>
    <li>Bread</li>
    <li class='fade'>Chips</li>

    <li class='fade'>Socks</li>
  </ul>
<script>
$("li").hover(
  function () {
    $(this).append($("<span> ***</span>"));
  }, 
  function () {
    $(this).find("span:last").remove();
  }
);



//li with fade class
$("li.fade").hover(function(){$(this).fadeOut(100);$(this).fadeIn(500);});

</script>
</body>
</html>

修改:

使用以下函数中使用的toggle将为您完成工作

<!DOCTYPE html>
<html>
<head>
  <style>
p { background:#dad;
font-weight:bold;
font-size:16px; }
</style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
 <button>Toggle 'em</button>

<p>Hiya</p>
<p>Such interesting text, eh?</p>
<script>
$("button").click(function () {
$("p").toggle("slow");
});    
</script>
</body>
</html>