jQuery

【jQuery】シンプルなパララックスjQuery SimpleParallax

December 5, 2017
Simple Parallax using jQuery

jQuery SimpleParallaxはjQueryを使ったシンプルなパララックスプラグイン。

JS

HTMLにjQueryとsimple.parallax.jsスクリプトを含める

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/simple.parallax.js"></script>

the jQuery

$.fn.sparallax = function(options) {
  var $window  = $(window),
      defaults = {
        $elements: $(this),
        speed: 4
      },
      settings = $.extend(defaults, options);

  $.each(settings.$elements, function(i, el) {
    var $el = $(el), offset = 0,
        speed = ($el.data('parallax-speed') ? $el.data('parallax-speed') : defaults.speed);

    $window.scroll(function() {
      offset = -($window.scrollTop() / speed);
      $el.css({ backgroundPosition: '50% ' + offset + 'px' });
    });
  });
};
$(document).ready(function() {
  $('.parallax').sparallax();
});

the css

.parallax {
  background-repeat: no-repeat;
  background-position: 50% 0;
  -webkit-transition: background-position .2s ease-in;
  -moz-transition: background-position .2s ease-in;
  -o-transition: background-position .2s ease-in;
  transition: background-position .2s ease-in;
  -webkit-background-size: cover;
  background-size: cover;
}

the html

<section class="parallax">
  <div>Your parallax container...</div>
</section>
<section class="parallax" data-parallax-speed="10">
  <div>Your parallax container...</div>
</section>

MIT