简体   繁体   中英

Change background image on hover and keep active

I'm new to all this and was hoping for some help. I want the background to stay after you hover one of the links. Also is it possible to make a fade/transition on the background when appearing?

 $(document).ready(function() { $('#change').hover(function() { $('body').css('background-image', 'url("http://i.imgur.com/cyxXVpT.jpg")'); }, function() { $('body').css('background', ''); }); $('#change2').hover(function() { $('body').css('background-image', 'url("http://i.imgur.com/5MupbQ2.jpg")'); }, function() { $('body').css('background', ''); }); }); 
 body { background-repeat: repeat; background-size:cover; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <a href="#" id="change">Change</a> <br> <a href="#" id="change2">Change2 </a> 

If you want the background to stay, just use the mouseenter event only

$('#change').on('mouseenter', function() {
    $('body').css('background-image', 'url("http://i.imgur.com/cyxXVpT.jpg")');
});

If you want fading backgrounds, you can use css transitions

-webkit-transition: background ease-in 1s;
-moz-transition: background ease-in 1s;
-o-transition: background ease-in 1s;
transition: background ease-in 1s;

FIDDLE

If you want keep the background don't use the 2nd parameter of hover function The first parameter of over is when you hover the object and the second on blur. https://api.jquery.com/hover/ It's possible to fade in using animate function https://api.jquery.com/animate/

EDIT: or a transition with css like adeneo said

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