2

I have some HTML set up like this:

<div class="mediasection large">
    <div class="cover" style="background-image: url(/media/images/panorama.jpg);"></div>
    <div class="overlay">Welcome!</div>
</div>

The cover element is uses background-attachment: fixed; to create a parallax effect. What I'm trying to achieve is have the overlay element behave the same way, where the text in it is fixed to the viewport, but still contained inside the mediasection div, so that when the user scrolls the page the cover and overlay stay in the same position, but disappear as the mediasection element goes out of view.

Is there any way to achieve this?

tl;dr; Some sort of background-attachment: fixed; to regular elements, not just the background.

Thanks!

4

2 回答 2

2

老实说,我认为最简单的方法就是使用 Photoshop / [您最喜欢的图像编辑软件] 将覆盖文本放在背景图像上。我做了这个 jsfiddle,希望能展示你想要的行为。

的HTML


<div class="media-screen">
    <h1 class="sr-only">Overlay Text</h1>
    <p class="sr-only">With an interesting paralax effect</p>
</div>

哪里sr-only是一个在视觉上隐藏元素同时保持屏幕阅读器可访问性的类

CSS


.media-screen {
    position: relative;
    height: 250px;
    background-image: url('path/to/your/image.png');
    background-position: center center;
    background-repeat: no-repeat;
    background-attachment: fixed;
}

.sr-only { 
    position: absolute; 
    overflow: hidden; 
    clip: rect(0 0 0 0); 
    height: 1px; width: 1px; 
    margin: -1px; padding: 0; border: 0; 
}

移动支持


如果您支持多种屏幕尺寸,您可能需要几个不同版本的图像来适应不同的方向。您可以使用媒体查询来替换为各种尺寸/方向显示的图像

/*Example media query for view port width*/
@media screen only and (min-width: 1024px){
    .media-screen {
        background-image: url('path/to/your/image-large.png');
    }
}

/* Example media query for view port orientation */
@media screen only and (orientation: portrait){
    .media-screen {
        background-image: url'path/to/your/image-narrow.png');
    }
}

注意:在背景图像中嵌入内容显然意味着内容不是交互式的,因此这仅对基本显示元素有任何好处。

于 2015-11-29T23:32:59.857 回答
0

我自己找到了一个基于 jQuery 的解决方案。我仍然不喜欢依赖 JavaScript,所以欢迎任何其他答案,但它确实有效。

这里是:

var oldScroll = 0;
$(window).scroll(function() {
    var scroll = $(window).scrollTop();
    var scrollOffset = scroll - oldScroll;

    // Overlay positions
    var offset = $(".overlay").offset();
    $(".overlay").offset({top: offset.top + scrollOffset});

    oldScroll = scroll;
});

这会在滚动时偏移覆盖。

但正如我所说,欢迎其他答案。

于 2015-11-30T01:49:54.663 回答