@ligisayan

Как анимировать фон состоящий из 2ух картинок?

Пытаюсь сделать parallax из двух фоновых картинок для первой секции (при фоне из 1 картинки все норм), но не знаю как их правильно анимировать, т.е. прописать позиционирование background-position сразу для 2ух частей фона, чтобы один на другой наслаивался и с разной скоростью скроллился.
Фидл
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="section-1" id="container">
  Lets start!
</div>
<div class="container section-2">
  There is more cool stuff below...
</div>
<div class="container section-3">
  We are done with cool things!
</div>

var velocity = 0.5;

function update() {
  var pos = $(window).scrollTop();
  $('.container').each(function() {
    var $element = $(this);
    var height = $element.height() - 18;
    $(this).css('backgroundPosition', '50% ' + Math.round((height - pos) * velocity) + 'px');
  });
  $('#container').css('backgroundPosition', '50% ' + Math.round(($('#container').height() - pos) * velocity) + 'px' + '50% ' + Math.round(($('#container').height() - pos / 2) * velocity) + 'px');
};

$(window).bind('scroll', update);

.container,
#container {
  padding: 200px 20px 200px 20px;
  text-align: center;
  color: #FFF;
  font-weight: bold;
}

.section-1 {
  background: url(https://www.logaster.ru/blog/wp-content/uploads/2014/06/img_514.png), url(http://static4.wikia.nocookie.net/__cb20130612023354/harrypotter/images/d/d1/Gradient-blue-background.jpg);
  background-position: center, center;
}

.section-2 {
  background-image: url(http://th00.deviantart.net/fs49/PRE/f/2009/207/e/d/Orange_Desktop_Background_by_The_Dogfather.png);
  background-position: center;
}

.section-3 {
  background-image: url(http://oaklandbaptist.org/media/Green-Background.jpg);
  background-position: center;
}
  • Вопрос задан
  • 131 просмотр
Решения вопроса 1
lamer350
@lamer350
กำลังสูงสุด
Проще всего внедрить какой нибудь валидный параметр для div, например data-speed.
Тоисть в HTML ваш DIV выглядел бы так:
<div class="section-1" id="container" data-speed="1">

Это некий коэффициент, который вы можете регулировать как вам угодно, к примеру 0.5 если поставить - будет скролится в 2 раза медленнее, а если поставить 3 - будет скроллится в 2 раза быстрее.
Тогда js код будет выглядеть так:
function update() {
  var pos = $(window).scrollTop();
  $('.container').each(function() {
    var $element = $(this);
    var height = $element.height() - 18;
    var speed - $element.attr('data-speed');
    $(this).css('backgroundPosition', '50% ' + Math.round((height - pos*speed) * velocity) + 'px');
  });
  $('#container').css('backgroundPosition', '50% ' + Math.round(($('#container').height() - pos*speed) * velocity) + 'px' + '50% ' + Math.round(($('#container').height() - (pos*speed) / 2) * velocity) + 'px');
};

если кратко, чтобы легче было найти в чем отличии, вводите новую переменную speed и все pos умножаете на speed
И потом в HTML методом перебора коэффициентов добиваетесь нужного вам эффекта.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы