2017-10-17 58 views
6

Here is my fiddle在固定背景圖像上滾動時,我可以使文本顯示爲固定嗎?

我試圖創建一個網頁,用戶可以滾動瀏覽多個覆蓋HTML元素似乎是固定的(不移動滾動)的全屏幕圖像。

在我的小提琴中,你可以看到我目前的文字位置是絕對的,它們相對於他們的父母移動。相反,我想將文本放置在每個背景圖像上,然後當用戶向下滾動時,文本保持固定,然後被下一部分(取決於方向)覆蓋/未覆蓋。

我的確嘗試使用position: fixed和z-index值,但是當我希望固定元素只能用自己的幻燈片顯示時,我總能看到固定元素。

添加文本與圖像文件不符合我的要求,因爲最終我想動態文本和視頻元素在這些固定的元素。非常感謝您的見解。

回答

2

你不能這樣做使用純CSS。請看這個片段。

$(window).scroll(function() { 
 
    $("section .cover-text").each(function() { 
 
    var marginTop = $(window).scrollTop() - $(this).parent().position().top; 
 
    $(this).css({ 
 
     'margin-top': marginTop 
 
    }); 
 
    }); 
 
});
#slide-1, 
 
#slide-2, 
 
#slide-3 { 
 
    position: relative; 
 
    overflow: hidden; 
 
} 
 

 
.cover-1, 
 
.cover-2, 
 
.cover-3 { 
 
    background-repeat: no-repeat; 
 
    background-attachment: fixed; 
 
    background-size: cover; 
 
    height: 100vh; 
 
} 
 

 
.cover-1 { 
 
    background-image: url('http://placekitten.com/800/350'); 
 
    z-index: 3000; 
 
} 
 

 
.cover-2 { 
 
    background-image: url('http://placekitten.com/g/800/350'); 
 
} 
 

 
.cover-3 { 
 
    background-image: url('http://placekitten.com/800/355'); 
 
} 
 

 
.cover-text { 
 
    font-size: 25px; 
 
    color: #FFFFFF; 
 
    text-shadow: 0 0 30px #000000; 
 
    position: absolute; 
 
    left: 20%; 
 
    top: 50%; 
 
    -webkit-transform: translate(-50%); 
 
    -moz-transform: translate(-50%); 
 
    -ms-transform: translate(-50%); 
 
    transform: translate(-50%); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<section id="slide-1"> 
 
    <div class="cover-1"></div> 
 
    <div class="cover-text">Title 1</div> 
 
</section> 
 
<section id="slide-2"> 
 
    <div class="cover-2"></div> 
 
    <div class="cover-text">Title 2</div> 
 
</section> 
 
<section id="slide-3"> 
 
    <div class="cover-3"></div> 
 
    <div class="cover-text">Title 3</div> 
 
</section>

+1

其良好。好夥伴 – Kumar

+0

@Kumar謝謝:) –

+0

非常感謝!這正是我想要做的。 – Davyd