我们已经看到了数千个看起来很棒的视差效果,但所有这些效果都涉及不同的div。 有没有办法在它上面有一个常规的全尺寸背景图像和文本(或任何内容)。当您滚动时,内容/文本会以不同的方式移动到背景(稍微)。 使用尽可能少的代码。
E.g。像http://jsfiddle.net/JSDesign/c7atw4u4/
这样的东西,但只有一个普通的全屏背景(封面或其他),如果没有必要,也没有滚动条等。
(function($) {
$.fn.parallax = function(options) {
var windowHeight = $(window).height();
// Establish default settings
var settings = $.extend({
speed : 0.05
}, options);
// Iterate over each object in collection
return this.each( function() {
// Save a reference to the element
var $this = $(this);
// Set up Scroll Handler
$(document).scroll(function(){
var scrollTop = $(window).scrollTop();
var offset = $this.offset().top;
var height = $this.outerHeight();
// Check if above or below viewport
if (offset + height <= scrollTop || offset >= scrollTop + windowHeight) {
return;
}
var yBgPosition = Math.round((offset - scrollTop) * settings.speed);
// Apply the Y Background Position to Set the Parallax Effect
$this.css('background-position', 'center ' + yBgPosition + 'px');
});
});
}
// THIS PART WOULD GO AT THE BOTTOM OF THE HTML PAGE (INSIDE <script> TAGS)
$('.parallax').parallax({
speed : 0.05
});
}(jQuery));
&#13;
html {width: 100%; height: 100%; }
.parallax {
height: 1600px; /* THIS CAN BE SHORTER IN A REAL DOC */
background-position: center top;
background-repeat: no-repeat;
background-attachment: fixed;
background-image: url('https://unsplash.imgix.net/reserve/m6rT4MYFQ7CT8j9m2AEC_JakeGivens%20-%20Sunset%20in%20the%20Park.JPG?q=75&fm=jpg&auto=format&s=0798c4e39d1acb580b25a93863dcae97');
background-size: cover;
padding-top: 180px;
}
.parallax h1 {
font-size: 200%;
text-align: center;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="parallax">
<h1>A Riveting Title</h1>
</section>
&#13;