jquery - 如何将淡入/淡出添加到鼠标悬停背景更改代码

标签 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>

如何向此代码添加淡入和淡出(鼠标移开时)效果?

谢谢!

最佳答案

<强> Working jsFiddle Demo

为您的背景容器添加另一个元素并更改其不透明度。

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

关于jquery - 如何将淡入/淡出添加到鼠标悬停背景更改代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17016326/

相关文章:

javascript - jQuery 中的 this 关键字

jquery - 使用 jquery 在 html 文本中定义数字

html - CSS 背景。将内容框与封面相结合

javascript - 元素在加载时出现然后消失

javascript - 如何访问对象标签中加载的 HTML 元素?

javascript - 按钮无法在 Chrome 中工作(Jquery/Javascript/css/php)

android - 修改android xml中背景图片的透明度

css - 模板粉尘 : after inserting a template is not loaded images from css

jQuery淡入淡出重复

jquery - jquery fadeIn 是如何工作的?对 animate() 做同样的事情