悬停在元素上,淡出父div的背景

时间:2017-11-09 09:40:22

标签: jquery css background-image transition fade

我在全屏div上有一个»元素«。我想在div».section«的背景图像中悬停在»element«和淡入淡出上。只显示背景图像没问题,但我不知道如何添加淡入淡出动画。

$(function() {
  $('.element').hover(function() {
    $('.section').css('background-image', 'url(https://ih0.redbubble.net/image.87373734.8395/flat,800x800,075,t.jpg)');
  }, function() {
    // on mouseout, reset the background
    $('.section').css('background-image', '');
  });
});
.section {
  width: 400px;
  height: 400px;
  border: 1px solid black;
  text-align: center;
  transition: 1s ease all;
}

.element {
  margin-top: 45%;
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="section">
 <div class="element">hover me</div>
</div>

{{3}}

你可以帮帮我吗?

2 个答案:

答案 0 :(得分:4)

我已经更新了你的小提琴。

你可以单独使用CSS而不需要使用jquery。您可以使用pseudo element来获得所需的效果。

在这种情况下,如果您将子元素保留为.element,则显示父级的背景.section,您可以使用pointer-events指定在何种情况下(如果有的话)特定的图形元素可以成为鼠标事件的目标。 https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events

CSS:

.section {
  width: 400px;
  height: 400px;
  border: 1px solid black;
  text-align: center;
  transition: 1s ease all;
  position: relative;
  pointer-events: none;
}

.section:after {
    background: url(https://ih0.redbubble.net/image.87373734.8395/flat,800x800,075,t.jpg) repeat;
    content: "";
    opacity: 0;
    width: inherit;
    height: inherit;
    position: absolute;
    top: 0;
    left: 0;
    /* TRANSISITION */
    transition: opacity 1s ease-in-out;
    -webkit-transition: opacity 1s ease-in-out;
    -moz-transition: opacity 1s ease-in-out;
    -o-transition: opacity 1s ease-in-out;
}

.element {
  position: relative;
  top: 50%;
  z-index: 1;
  pointer-events: auto;
}

.section:hover:after{   
    opacity: 1;
}

https://jsfiddle.net/sr1qj1pc/3/

答案 1 :(得分:0)

另一种快速方法 -

   $(function() {
  $('.element').hover(function() {
    var section =  $('.section');
    section.fadeOut(0, function(){
        section.css('background-image', 'url(https://ih0.redbubble.net/image.87373734.8395/flat,800x800,075,t.jpg)');
        section.children().fadeIn();
        section.fadeIn(1500);
    });
  }, function() {
    // on mouseout, reset the background
    $('.section').css('background-image', '');
  });
});