Change multiple background-images with jQuery

2019-07-05 01:07发布

In my css page, i have this as code:

header {
    background:url('afbeeldingen/r.png'),url('Afbeeldingen/black.jpg');
    background-position: 50% 33%, left top;
    background-repeat: no-repeat, no-repeat;
    background-size:26%,960px 130px;
    margin-left:auto;
    margin-right:auto;
}

Now in my html page, I want to use JQuery to change the first image when I hover my navigation bar. Can you please help me?

2条回答
祖国的老花朵
2楼-- · 2019-07-05 01:42

There is no current native method in jQuery to switch out the order of the background images (and hence the one that is displayed). Here's the code to swap the background image order for an element with two background images by parsing the links and swapping them:

var bg=$(this).css('background-image').split('),url(');
if(bg.length==2) $(this).css('background-image','url('+bg[1]+','+bg[0]+')');
查看更多
ら.Afraid
3楼-- · 2019-07-05 01:45

Use class header to your navigation button wherever you want to do this work

.header {
    background:url('afbeeldingen/r.png'),url('Afbeeldingen/black.jpg');
    background-position: 50% 33%, left top;
    background-repeat: no-repeat, no-repeat;
    background-size:26%,960px 130px;
    margin-left:auto;
    margin-right:auto;
}


<script>
$(".header").hover(function(){
   $(this).css("background","url('Afbeeldingen/black.jpg'),url('Afbeeldingen/anotherhoverimage.jpg')"); 
});

$(".header").mouseout(function(){
   $(this).css("background","url('afbeeldingen/r.png'),url('Afbeeldingen/black.jpg')"); 
});
</script>
查看更多
登录 后发表回答