so on my site I created a functionality where when I hover on one of the side buttons the image of the tree in the middle changes. You can see the page here.
The animation is working ok, but now I am trying to make the background image responsive within the div. Thanks to this other jsfiddle , I was able to make the original background image responsive using the following CSS:
#arvore {
background: url('http://vistacamisa.greenpeace.org.br/wp-content/uploads/2015/09/arvore_011.png');
background-size: contain;
background-repeat: no-repeat;
width: 100%;
height: 0;
padding-top: 92.7%;
}
The problem is that this CSS does not apply to the image that shows when I hover on the button, and I've hit a roadblock as to how to make it work. Any ideas or suggestions would be much appreciated!
I'm using the following jQuery:
<script type="text/javascript">
(function($){
$('.arvorehover').hover(function(){
$('#arvore').css({'background':'url('+ $(this).attr('target') +')'});
},function(){
$('#arvore').css({'background':''});
});
})(jQuery)
</script>
My buttons have a class .arvorehover and the div with the tree image has the id #arvore.
Thanks so much!
When you set the hover background in your JavaScript using this:
$('#arvore').css({'background':'url('+ $(this).attr('target') +')'});
...it adds a style attribute to the tag: <div id="arvore" style="background:url(....)">
, which overrides your entire CSS background
declaration, which in turn sets background-size
to auto
. You can fix your current code by changing only the background-image
property:
<script type="text/javascript">
(function($){
$('.arvorehover').hover(function(){
$('#arvore').css({'background-image':'url('+ $(this).attr('target') +')'});
},function(){
$('#arvore').css({'background-image':''});
});
})(jQuery)
</script>
Alternately you can keep the styling in your CSS by toggling a class in your JavaScript:
<script type="text/javascript">
(function($){
$('.arvorehover').hover(function(){
$('#arvore').addClass('hover');
},function(){
$('#arvore').removeClass('hover')
});
})(jQuery)
</script>
And then in your CSS:
#arvore.hover {
background-image: url("some-url");
}
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.