[英]Parallax scroll working on 1 image but not on other
我正在為我的2個背景圖像提供視差效果,並且它在第一個圖像上工作,但不在第二個圖像上工作。代碼如下
jQuery的:
$(document).ready(function() {
$('section[data-type="background"]').each(function() {
var $bgobj = $(this); // assigning the object
$(window).scroll(function() {
// scroll the background at var speed
// the yPos is a negative value because we're scrolling it UP!
var yPos = -($window.scrollTop() / $bgobj.data('speed'));
// Put together our final background position
var coords = '50% '+ yPos + 'px';
// Move the background
$bgobj.css({ backgroundPosition: coords });
}); // end window scroll
});
});
HTML:-
<section class="parallax" data-type="background" data-speed="5">
<h2>Check out this cool parallax scrolling effect. Use these ribbons to display calls to action mid-page.</h2>
<button class="btn btn-lg btn-info">PARALLAX</button>
</section>
CSS:
.parallax {
height:35em;
background: url('https://images.unsplash.com/photo-1463123081488-789f998ac9c4?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&s=6d1a6d1c5a7eb63d0c411b1d019f0b30');
background-repeat: no-repeat;
background-position: center center;
background-size: cover;
}
.parallax h2 {
color: white;
text-align: center;
padding: 1em;
padding-top: 5em;
}
.parallax button {
display: block;
margin: 2em auto;
}
奇怪的是,第二張圖片根本不顯示,僅當我刪除了data-speed屬性后才顯示,但視差不起作用。.我感到困惑和困惑,請協助。
您正在使用$ window.scrollTop(),當您向下滾動頁面並相對於圖像容器的頂部設置該值時,它會變得更大。 似乎您需要先從文檔頂部減去元素位置:
$(document).ready(function() {
$('section[data-type="background"]').each(function() {
var $bgobj = $(this); // assigning the object
$(window).scroll(function() {
// scroll the background at var speed
// the yPos is a negative value because we're scrolling it UP!
var yOffset = $bgobj.offset().top;
var yPos = -(($window.scrollTop() - yOffset) / $bgobj.data('speed'));
// Put together our final background position
var coords = '50% '+ yPos + 'px';
// Move the background
$bgobj.css({ backgroundPosition: coords });
}); // end window scroll
});
});
您的第一張圖像很可能因為它位於頁面頂部而起作用,因此偏移量無關緊要嗎?
嘗試這個
$(document).ready(function() {
$(window).scroll(function() {
$('section[data-type="background"]').each(function(i,e) {
// scroll the background at var speed
// the yPos is a negative value because we're scrolling it UP!
var yPos = -($(window).scrollTop() / $(e).data('speed'));
// Put together our final background position
var coords = '50% '+ yPos + 'px';
// Move the background
$(e).css({ backgroundPosition: coords });
});
}); // end window scroll
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.