【问题标题】:Hover on element, fade in background on parent div悬停在元素上,在父 div 上淡入背景
【发布时间】:2017-11-09 18:41:49
【问题描述】:

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

$(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>

https://jsfiddle.net/sr1qj1pc/

你能帮帮我吗?

【问题讨论】:

标签: jquery css background-image transition fade


【解决方案1】:

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

你可以单独使用 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/

【讨论】:

  • 谢谢,但这不是我想要的。我想将鼠标悬停在 div ».element« 上并淡入 div ».section« 的背景
【解决方案2】:

另一种快速方法 -

   $(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', '');
  });
});

【讨论】:

    猜你喜欢
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    相关资源
    最近更新 更多