jquery - 如何将fadein / fadeout添加到mouseover后台更改代码

时间:2013-06-10 02:59:46

标签: jquery background-image fadein fadeout

我有这段代码,当您将鼠标悬停在链接上时会更改div的背景图片:

<script>

$('.main').on('mouseover', 'a', function () {

var background = "url('" + $(this).attr('data-background') + "')";

$('.main').css('background-image', background)
});

</script>

和html一起使用..

<div style="background: #f2f2f2 no-repeat center; background-size:100% auto;" class="main">
<div id="logo"></div>
<div class="center-inner">
<h3>
<a href="#" data-background="img/img1.jpg">img1</a> 
<a href="#" data-background="img/img2.jpg">img2</a> 
<a href="#" data-background="img/img3.jpg">img3</a>
</h3></div>
<div id="copyright"><p>©2013</p></div>
</div>

如何在此代码中添加淡入和淡出(鼠标输出)效果?

谢谢!

1 个答案:

答案 0 :(得分:0)

<强> Working jsFiddle Demo

background容器添加另一个元素并更改其不透明度。

HTML

<div class="main">
    <div id="bg"></div>
    <div id="logo"></div>
    <div class="center-inner"><h3>
        <a href="#" data-background="http://placekitten.com/200/200">img1</a> 
        <a href="#" data-background="http://placekitten.com/200/200">img2</a> 
        <a href="#" data-background="http://placekitten.com/200/200">img3</a>
    </h3></div>
    <div id="copyright"><p>©2013</p></div>
</div>

CSS

.main, #logo, .center-inner, #copyright {
    position: relative;
}

#bg {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: #f2f2f2 no-repeat center; background-size:100% auto;
}

的JavaScript

$(function () {
    $('.main').on('mouseover', 'a', function () {
        var background = "url('" + $(this).attr('data-background') + "')";

        $('#bg')
            .stop()
            .css('opacity', 0)
            .css('background-image', background)
            .animate({opacity: 1});
    });
});