JQuery 悬停函数不透明度动画

JQuery hover function opacity animation

本文关键字:动画 不透明度 函数 悬停 JQuery      更新时间:2023-09-26

尝试在悬停其他元素时对divs opacity进行动画处理。首先,我用 display none/block 尝试了它,但它在某处读到不可能为此进行过渡。

这有点复杂,因为这应该适用于具有不同 id 的相同类型的每个元素。(将图片悬停在 img 元素底部的带有标题的图片库。

HTML 结构如下所示:

<article id="{PostID}">
    <div class="post-content">
        <a><img></a>
        <div class="post-content--padded">
            <p>Caption of the picture.</p>
        </div>
    </div>
</article>

首先,我用了一个mouseovermouseout方法添加到post-content div中,看起来像这样:

onmouseover="document.getElementById('{PostID}').getElementsByClassName('post-content--padded')[0].style.opacity='1.0';" onmouseout="document.getElementById('{PostID}').getElementsByClassName('post-content--padded')[0].style.opacity='0.0';"

这奏效了,但没有transition.我已经使用过渡处理程序设置了 CSS,以应用于post-content--padded中的所有 css 更改,如下所示:

-webkit-transition: all 0.3s;
-moz-transition: all 0.3s;
transition: all 0.3s;

这似乎不会影响mouseovermouseout不透明度更改,所以我尝试添加.animate(),但没有多大成功。好吧,我有post-content淡入淡出,但不是post-content--padded

不同的方法

这一切都没有那么多作用。所以我尝试使用 JQuery 函数hover() .长话短说,我在有问题的 html 上方添加了这个:

<script type="text/javascript">
$(document).ready(function(){
    $('#{PostID}.post-content').hover(
    function(){ $('#{PostID}.post-content.post-content--padded').stop().animate({'opacity': '1'}, 'slow');},
    function(){ $('#{PostID}.post-content.post-content--padded').stop().animate({'opacity': '0'}, 'slow');}
    );
 });
</script>

不过,这只是不想工作。无休止地浏览stackoverflow和其他来源似乎对我没有帮助。被困了一个多小时,我决定简单地问。添加悬停>操作过渡并不难。

希望我不清楚,人们在这里理解我的问题。

如果您只需要悬停,则可以使用 CSS 进行操作

.post-content--padded{
    opacity: 0;
    -webkit-transition: all 2s;
    -moz-transition: all 2s;
    transition: all 2s;
}
.post-content:hover .post-content--padded{
    opacity: 1;
    -webkit-transition: all 2s;
    -moz-transition: all 2s;
    transition: all 2s;
}

在此处查看演示

如果你想使用Jquery

$('.post-content--padded').hide();
$('.post-content').hover(function(){
    $(this).find('.post-content--padded').fadeToggle(2000);
});

在此处查看演示

我还致力于将悬停与 animate 相结合,它的工作原理是这样的:

在 CSS 中,"a" = 0 的不透明度

在jQuery中:

$("#classy").hover(function(){
      $("#classy").animate({
          opacity:"1"
      },200);
  }, function(){
      $("#classy").animate({
          opacity:"0"
      },200);
  });

下面是一个有效的jQuery方法:

.HTML

<div id='hover-me'>hover over me</div>
<div id='change-me'>I change opacity</div>

.CSS

.hide {
    opacity:0;
}

.JS

$('#hover-me').hover( function() {
    if ($('#change-me').hasClass('hide')) {
        $('#change-me').removeClass('hide', 'slow');
    } else {
        $('#change-me').addClass('hide', 'slow');
    }
});

jsFiddle 演示

*这是包含jQueryUI的