简体   繁体   中英

Transition background image on hover

I'm trying to find a way to transition from one background image to another when I hover a div.

Here's a demo:

codepen demo

Here's my code

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

Any ideas?

First, you are missing IDs for your <h1> , because your JQuery select elements with ID cat, dog and rabbit. seccond, what you should change is background of '.bg' class, not '.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')");
});

demo : 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM