Создаем эффект паралакса

Данный эффект можно применить к любому элементу. Например логотипу, фону и прочим мелочам.

Шаг 1. HTML

Для начала мы создадим простую разметку, следует заметить, что для простоты разметки мы упростили код вывода изображений, все изображения имеют одинаковый артикул кроме последнего символа, по этому мы указываем вывод изображения по первым цифрам, а в конце указываем *.png. Это позволяет считать все изображения заданного диапазона.

Код
<div class="wrapper">
<div class="example text">
  <a href="#" class="parallax" data-imgname="img/4-6-*.png" data-levels="8" data-space="30"> </a>
  <a href="#" class="parallax" data-imgname="img/7-10-*.png" data-levels="8" data-space="30"></a>
  </div>
</div>

Шаг 2. CSS

Со стилями все не так сложно, так как основную часть работы будет выполнять JS и jQuery, для этого мы установим параметры контейнера и его позиционирование:

Код
.container {
  width: 354px;
  height: 585px;
  position: relative;
  margin: 0 auto;
}
.back {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background:rgb(91,145,179);
background:-webkit-gradient(linear, 0 0, 0 100%, from(rgba(91,145,179,1)), color-stop(0.5, rgba(146,187,219,1)), color-stop(0.75, rgba(118,137,196,1)), to(rgba(37,67,127,1)));
background:-webkit-linear-gradient(rgba(91,145,179,1) 0%, rgba(146,187,219,1) 50%, rgba(118,137,196,1) 75%, rgba(37,67,127,1) 100%);
background:-moz-linear-gradient(rgba(91,145,179,1) 0%, rgba(146,187,219,1) 50%, rgba(118,137,196,1) 75%, rgba(37,67,127,1) 100%);
background:-o-linear-gradient(rgba(91,145,179,1) 0%, rgba(146,187,219,1) 50%, rgba(118,137,196,1) 75%, rgba(37,67,127,1) 100%);
background:linear-gradient(rgba(91,145,179,1) 0%, rgba(146,187,219,1) 50%, rgba(118,137,196,1) 75%, rgba(37,67,127,1) 100%);
filter:progid:DXImageTransform.Microsoft.gradient( startColorstr='#5b91b3', endColorstr='#25437f',GradientType=0 );
}
.back span {
  display: block;
  position: absolute;
  border-radius: 50%;
}
.content {
  display: block;
  color: white;
  text-align: center;
  position: absolute;
  width: 100%;
  height: 100%;
  font-family: Helvetica Neue, Helvetica, Arial;
  font-weight: 100;
}
.hour {
  font-size: 120px;
  line-height: 100px;
  margin: 30px 0 0 0;
  padding: 0;
  font-weight: inherit;
}
.date {
  font-size: 20px;
}
.top-bar {
  padding: 10px 5px;
  width: 100%;
  text-align: left;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  -o-box-sizing: border-box;
  box-sizing: border-box;
  box-sizing: border-box;
  overflow: hidden;
}
.signal {
  float: left;
}
.battery {
  display: block;
  float: right;
  width: 25px;
  height: 8px;
  outline: 1px solid white;
  outline-offset: 1px;
  border-radius: 1px;
  background: white;
  position: relative;
  margin-right: 5px;
  margin-top: 5px;
}
.battery:after {
  content: " ";
  position: absolute;
  right: -6px;
  width: 3px;
  height: 6px;
  top: 1px;
  background: white;
  display: block;
  border-radius: 0 50% 50% 0;
}
.slide-container {
  position: absolute;
  bottom: 100px;
  font-size: 40px;
  width: 100%;
  text-align: center;
}
.slide {
  display: block;
  width: 100%;
  -moz-background-clip: text;
-webkit-background-clip: text;
-moz-text-fill-color: transparent;
-webkit-text-fill-color: transparent;
-webkit-animation: slidetounlock 5s infinite linear;
background-position: -600px;
}
@-webkit-keyframes slidetounlock {
  0% {
  background-position: -600px 0;
  }
  100%{
  background-position: 600px 0;
  }
}

Как Вы заметили мы установим позиционирование фона, и некоторую градиентную заливку для слоев с различной поддержкой браузеров.

Шаг 3. JS

Нам необходимо все это собрать в кучу и привести в работу, для этого нам понадобится небольшие правила JavaScript, с помощью которых мы реализуем работу параллакса.

Код
if ("undefined" != typeof jQuery) {
  (function(a) {
  a.imgpreload = function(b, c) {
  c = a.extend({}, a.fn.imgpreload.defaults, c instanceof Function ? {
  all: c
  } : c);
  if ("string" == typeof b) {
  b = [b]
  }
  var d = [];
  var e = b.length;
  for (var f = 0; f < e; f++) {
  var g = new Image;
  a(g).bind("load error", function(b) {
  d.push(this);
  a.data(this, "loaded", "error" == b.type ? false : true);
  if (c.each instanceof Function) {
  c.each.call(this)
  }
  if (d.length >= e && c.all instanceof Function) {
  c.all.call(d)
  }
  });
  g.src = b[f]
  }
  };
  a.fn.imgpreload = function(b) {
  var c = [];
  this.each(function() {
  c.push(a(this).attr("src"))
  });
  a.imgpreload(c, b);
  return this
  };
  a.fn.imgpreload.defaults = {
  each: null,
  all: null
  }
  })(jQuery)
}
// DOM ready
$(document).ready(function() {
  var _ParallaxHover = function(el) {
  // Set up handle
  var t = this,
  $orig = $(el);
  // Extend object with handy variables
  t.$link = $orig.clone().addClass('enhanced');
  t.levels = parseInt(t.$link.data('levels'));
  t.space = parseInt(t.$link.data('space'));
  t.imgName = t.$link.data('imgname');
  t.images = new Array();
  t.pos = $orig.offset();
  t.dim = {
  w: $orig.outerWidth(),
  h: $orig.outerHeight()
  };
  t.$levels = $();
  t.threshold = 1;
  t.cPos = {
  x: t.dim.w / 2,
  y: t.dim.h / 2
  };
  t.tPos = {
  x: t.cPos.x,
  y: t.cPos.y
  };
  t.vPos = {
  x: 0,
  y: 0
  };
  t.interval;
  t.isLooping = false;
  // Set up elements and bind events
  if (t.levels > 0 && t.space > 0 && t.imgName.indexOf('*') > -1) {
  for (var i = 0; i < t.levels; i++) {
  (function() {
  var levelImgName = t.imgName.replace('*', i),
  index = i + 1,
  mid = Math.round(t.levels / 2),
  dist = (index - mid) / (t.levels - mid),
  $level = $('<span />').addClass('level').data('dist', dist).css('background-image', 'url(' + levelImgName + ')').prependTo(t.$link);
  t.$levels.push($level);
  t.images.push(levelImgName);
  })();
  }
  t.$link.mousemove(function(e) {
  var mPos = {
  x: e.pageX,
  y: e.pageY
  },
  xPos = mPos.x - t.pos.left,
  yPos = mPos.y - t.pos.top;
  t.tPos = {
  x: xPos,
  y: yPos
  };
  t.startAnimationLoop();
  }).mouseenter(function() {
  t.startAnimationLoop();
  }).mouseleave(function() {
  t.tPos.x = t.dim.w / 2;
  t.tPos.y = t.dim.h / 2;
  });
  $.imgpreload(t.images, function() {
  $orig.replaceWith(t.$link);
  });
  }
  // Return object
  return this;
  };
  _ParallaxHover.prototype.animateTo = function(x, y) {
  var t = this;
  t.tPos = {
  x: x,
  y: y
  };
  t.startAnimationLoop();
  };
  _ParallaxHover.prototype.startAnimationLoop = function() {
  var t = this;
  if (!t.isLooping) {
  t.isLooping = true;
  t.interval = setInterval(function() {
  t.animationLoop();
  }, 35);
  }
  };
  _ParallaxHover.prototype.setPosition = function() {
  var t = this;
  t.$levels.each(function() {
  var $level = $(this);
  $level.css({
  'top': -((t.cPos.y / t.dim.h) * 2 - 1) * t.space * $level.data('dist'),
  'left': -((t.cPos.x / t.dim.w) * 2 - 1) * t.space * $level.data('dist')
  });
  });
  return t.cPos;
  };
  _ParallaxHover.prototype.animationLoop = function() {
  var t = this,
  x = (t.tPos.x - t.cPos.x),
  y = (t.tPos.y - t.cPos.y);
  t.vPos.x *= 0.7;
  t.vPos.y *= 0.7;
  x *= 0.10;
  y *= 0.10;
  t.vPos.x += x;
  t.vPos.y += y;
  t.cPos.x += t.vPos.x;
  t.cPos.y += t.vPos.y;
  if (t.vPos.x >= t.threshold || t.vPos.y >= t.threshold || t.vPos.x <= -t.threshold || t.vPos.y <= -t.threshold) {
  t.setPosition();
  } else {
  t.isLooping = false;
  clearInterval(t.interval);
  }
  };
  $('.parallax').each(function() {
  window.parallaxHover = new _ParallaxHover(this);
  });
});

Вот и все!!

  • FalleN

  • 1941

  • 1

  • 194

Ссылки на статью:

Похожие статьи: