悬停时的过渡背景图像

Transition background image on hover

我正在尝试找到一种方法,当我将鼠标悬停在 div 时从一个背景图像过渡到另一个背景图像。

这是一个演示:

codepen demo

这是我的代码

$('#cat').hover(function(){
  $('.image').css('background-image', 
    "url('https://images.unsplash.com/photo-1485198963969-3f6b12e49abb')");
});

有什么想法吗?

首先,您缺少 <h1> 的 ID,因为您的 JQuery select 元素的 ID 为猫、狗和兔子。 其次,你应该改变的是'.bg' background class,而不是'.image' class

HTML

<h1 id="cat">CAT</h1>
<h1 id="dog">DOG</h1>
<h1 id="rabbit">RABBIT</h1>

JS

$('#cat').hover(function(){
    $('.bg').css('background-image', "url('https://images.unsplash.com/photo-1485198963969-3f6b12e49abb')");
});

$('#dog').hover(function(){
    $('.bg').css('background-image', "url('https://images.unsplash.com/photo-1469225208447-8329cbd3cb3a')");
});

$('#rabbit').hover(function(){
    $('.bg').css('background-image', "url('https://images.unsplash.com/photo-1478754351612-f8b7577a3859')");
});

演示:https://jsfiddle.net/z2hevmya/

var images = {
  "cat":'https://images.unsplash.com/photo-1485198963969-3f6b12e49abb',
  "dog" : 'https://images.unsplash.com/photo-1469225208447-8329cbd3cb3a',
  "rabbit" : 'https://images.unsplash.com/photo-1478754351612-f8b7577a3859'
};

$('.menu').hover(function(){
    var img = $(this).attr("id");
    $('.bg').css('background-image', "url(" + images[img] + ")");
});
body {
 margin: 0;
 padding: 0;
}

h1 {
 z-index: 100;
 color: #456;
 font-family: sans-serif;
 position: relative;
 opacity: .5;
 transition: all ease 1s;
 cursor: pointer;
 height: 1em;
 padding: .5em;
 margin: 0;
}

h1:hover {
 opacity: 1;
}

.bg {
 position: fixed;
 height: 100%;
 width: 100%;
 background: url('https://images.unsplash.com/photo-1485198963969-3f6b12e49abb') no-repeat center;
 background-size: cover;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="bg"></div>

<h1 id="cat" class="menu">CAT</h1>
<h1 id="dog" class="menu">DOG</h1>
<h1 id="rabbit" class="menu">RABBIT</h1>

<script language="javascript">
        $(function () {
            
            $('.mDiv').hover(function () {
                        $(this).addClass('divHover');
                    }, function () {
                         $(this).removeClass('divHover');
                    }
            );
        });
    </script>
<style type="text/css">
        .mDiv {
            height: 300px;
            width: 200px;
            background: darkgrey;
            border: solid 1px #ccc;
            float: left;
            margin-right: 10px;
        }
        .divHover{
        //  background-image: you " img url";
            background: greenyellow;

        }
    </style>
<div id="d">
    <div class="mDiv">Test</div>
</div>