在悬停时转换背景图片

时间:2017-06-03 03:07:59

标签: javascript jquery html css background-image

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

以下是演示:

codepen demo

这是我的代码

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

有什么想法吗?

3 个答案:

答案 0 :(得分:3)

首先,您缺少<h1>的ID,因为您的JQuery选择了ID为cat,dog和rabbit的元素。 第二,你应该改变的是'.bg'类的background,而不是'.image'类

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/

答案 1 :(得分:2)

&#13;
&#13;
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] + ")");
});
&#13;
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;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

&#13;
&#13;
<script language="javascript">
        $(function () {
            
            $('.mDiv').hover(function () {
                        $(this).addClass('divHover');
                    }, function () {
                         $(this).removeClass('divHover');
                    }
            );
        });
    </script>
&#13;
<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>
&#13;
<div id="d">
    <div class="mDiv">Test</div>
</div>
&#13;
&#13;
&#13;