演示地址:http://www.jq22.com/jquery-info1799
jquery插件,使用验证过可用。
分析源代码后总结原理:设置background样式为fixed,判断浏览器滚动距离,当在视窗范围内时,调用$(window).scroll。并根据所设置的速度比例,进行同步滚动。
调用时,设置三个必要参数:data-speed,data-type,background样式为fixed
<div data-speed="4" data-type="background" style="background:url(...) 50% 0 no-repeat fixed">
js会根据data-speed来计算滚动速度,越小越快。
可以根据不同的data-type作不同处理,可自定义写代码,很方便。
background必须是fixed。
parallax.js源代码(需先引入jQuery)
$(document).ready(function(){ // Cache the Window object
$window = $(window); // Cache the Y offset and the speed of each sprite
$('[data-type]').each(function() {
$(this).data('offsetY', parseInt($(this).attr('data-offsetY')));
$(this).data('Xposition', $(this).attr('data-Xposition'));
$(this).data('speed', $(this).attr('data-speed'));
}); // For each element that has a data-type attribute
$('section[data-type="background"]').each(function(){ // Store some variables based on where we are
var $self = $(this),
offsetCoords = $self.offset(),
topOffset = offsetCoords.top; // When the window is scrolled...
$(window).scroll(function() { // If this section is in view
if ( ($window.scrollTop() + $window.height()) > (topOffset) &&
( (topOffset + $self.height()) > $window.scrollTop() ) ) { // Scroll the background at var speed
// the yPos is a negative value because we're scrolling it UP!
var yPos = -($window.scrollTop() / $self.data('speed')); // If this element has a Y offset then add it on
if ($self.data('offsetY')) {
yPos += $self.data('offsetY');
} // Put together our final background position
var coords = '50% '+ yPos + 'px'; // Move the background
$self.css({ backgroundPosition: coords }); // Check for other sprites in this section
$('[data-type="sprite"]', $self).each(function() { // Cache the sprite
var $sprite = $(this); // Use the same calculation to work out how far to scroll the sprite
var yPos = -($window.scrollTop() / $sprite.data('speed'));
var coords = $sprite.data('Xposition') + ' ' + (yPos + $sprite.data('offsetY')) + 'px'; $sprite.css({ backgroundPosition: coords }); }); // sprites // Check for any Videos that need scrolling
$('[data-type="video"]', $self).each(function() { // Cache the video
var $video = $(this); // There's some repetition going on here, so
// feel free to tidy this section up.
var yPos = -($window.scrollTop() / $video.data('speed'));
var coords = (yPos + $video.data('offsetY')) + 'px'; $video.css({ top: coords }); }); // video }; // in view }); // window scroll }); // each data-type }); // document ready