jQuery fadeIn 不适用于 Z-index

标签 jquery html css

第二张图片怎么会淡入。我想这与z-indexopacity有关。

$(document).ready(function() {
    $(window).scroll(function() {
        $('.fade-in').each(function(i) {
            var bottom_of_object = $(this).position().top + $(this).outerHeight();
            var bottom_of_window = $(window).scrollTop() + $(window).height();
            /* If the object is completely visible in the window, fade it it */
            if (bottom_of_window > bottom_of_object-$(this).outerHeight()/2) {
                $(this).animate({
                    'opacity' : '1'
                }, 500);
            }
        });
    });
});
.fade-in {
    opacity:0 ;
}
.row {
    position: relative;
    width:100%;
    height: 600px;
    background: #000000;
}
.offset {
    height:1000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="offset">scroll down</div>

<div class="row">
    <img src="http://assets3.parliament.uk/iv/main-large//ImageVault/Images/id_7382/scope_0/ImageVaultHandler.aspx.jpg" alt="test" class="fade-in"/>
</div>

<img src="http://assets3.parliament.uk/iv/main-large//ImageVault/Images/id_7382/scope_0/ImageVaultHandler.aspx.jpg" alt="test" class="fade-in"/>

最佳答案

您遇到的问题与z-indexopacity 无关。

在您的代码中,您使用 .position() 方法找出要淡入的元素的坐标。作为documentation描述:

The .position() method allows us to retrieve the current position of an element relative to the offset parent.

如果将第一张图像的 .position().top() 打印到控制台,您将看到它始终为 0。这是因为它(第一张图片)相对于它的父 .row 元素有一个 0 的顶部偏移量。使您的动画自动触发。

为避免这种情况,您应该使用 .offset()方法而不是 .position(),因为它返回元素相对于 document 的坐标。通过这种方式,您可以使用 .rows 或其他布局模式的任意组合在滚动时触发效果。

希望对你有帮助。

– 全速

关于jQuery fadeIn 不适用于 Z-index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26028660/

相关文章:

html - 如何正确对齐 html 中的图像和文本?

javascript - 从 dom 元素获取窗口对象的引用

javascript - 使用ajax每X秒更新一次html页面

javascript - jQuery 查找子级并按顺序赋值

javascript - 在javascript中显示百分比弧

html - 是否有针对程序员的HTML教程?

html - 在内联跨度元素上指定高度的原因

javascript - 按下按钮时如何显示div的内容而不是值?

javascript - 光滑的 slider 宽度错误

html - 使用 CSS 绘制重叠的椭圆