Подтвердить что ты не робот

Прокрутка фонового изображения Parallax без использования свойства css background

Можно ли добавить эффект параллакса без использования свойств css background и background-attachment?

У меня есть тег img внутри div и вы хотите добавить эффект прокрутки параллакса к изображению, ниже приведен код

function resize_div()
{
    var image_height = $('.project-image img').height();

    var div_height = $('.project-image').height();
    var window_height = $(window).height();
    var window_width = $(window).width();

   
        $('.project-image').css('height', window_height - 80);
    
}

$(window).resize(function () {
        resize_div();
});
.project-details
{
  width:100%;
}
.project-image{
  text-align:center
}
.project-description
{
  line-height:15px;
  margin:0 0 10px
}
.img-responsive
{
  height: auto;
  max-width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="project-details">
  <div class="project-image">
   <img src="http://placehold.it/350X225" class="img-responsive">
  </div>  
  <h1>
  Project Title
  </h1>
  <p class="project-description">
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  <br/>
  <br/>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  <br/>
  <br/>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  </p>
</div>
4b9b3361

Ответ 1

Некоторое время назад я построил эти два примера с эффектом parralax, очень похожим на то, что вы ищете:

  • этот пример, используя простой jQuery, чтобы обновить положение изображения и названия в прокрутке
  • этот пример, используя только CSS с 3D-позиционированием, чтобы имитировать эффект параклакса на изображении

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

$( document ).ready(function() {
var $window = $(window);
function scroll_elements(){
  var scroll = $window.scrollTop();
  var scrollLayer = scroll/1.4;
  
  $(".project-image").css(
    "-webkit-transform","translate3d(0," +  scrollLayer  + "px,0)",
            "transform","translate3d(0," +  scrollLayer  + "px,0)"
  );
}

$window.scroll(scroll_elements);
});
.project-image {
  position:relative;
  z-index:1;
}
.img-responsive {
  display:block;
  max-width:100%; 
  height:auto;
  margin:0 auto;
}
h1, .project-description {
  position:relative;
  max-width:500px;
  z-index:2;
  background:rgba(255,255,255,.7);
  margin:0 auto;
  padding:10px 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="project-details">
  <div class="project-image">
   <img src="http://placehold.it/350X225" class="img-responsive">
  </div>  
  <h1>
  Project Title
  </h1>
  <p class="project-description">
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  <br/>
  <br/>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  <br/>
  <br/>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  </p>
</div>

Ответ 2

Хорошо, поэтому я попробовал что-то еще, и в этом конкретном случае он работает и, возможно, может быть лучшим решением:

*{
  margin: 0;
  padding: 0;
}

#image {
  width: 100%;
  position: fixed;
}

#image2 {
  width: 100%;
  position: relative;
  visibility:hidden;
}
#prl {
  position: relative;
  background-color: white;
}
  <img src="http://placehold.it/350X225" id="image">
  <img src="http://placehold.it/350X225" id="image2">

<div id="prl">
  <p>
  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsad
  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksdghjlsadv  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsad
  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksdghjlsadv  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsad
  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksdghjlsadv  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsad
  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksdghjlsadv
  </p>
</div>

Ответ 3

После некоторых поисков я нашел this

$('.img-parallax').each(function(){
  var img = $(this);
  var imgParent = $(this).parent();
  function parallaxImg () {
    var speed = img.data('speed');
    var imgY = imgParent.offset().top;
    var winY = $(this).scrollTop();
    var winH = $(this).height();
    var parentH = imgParent.innerHeight();


    // The next pixel to show on screen      
    var winBottom = winY + winH;

    // If block is shown on screen
    if (winBottom > imgY && winY < imgY + parentH) {
      // Number of pixels shown after block appear
      var imgBottom = ((winBottom - imgY) * speed);
      // Max number of pixels until block disappear
      var imgTop = winH + parentH;
      // Porcentage between start showing until disappearing
      var imgPercent = ((imgBottom / imgTop) * 100) + (50 - (speed * 50));
    }
    img.css({
      top: imgPercent + '%',
      transform: 'translate(-50%, -' + imgPercent + '%)'
    });
  }
  $(document).on({
    scroll: function () {
      parallaxImg();
    }, ready: function () {
      parallaxImg();
    }
  });
});
@import url(https://fonts.googleapis.com/css?family=Amatic+SC:400,700);
html, body{
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
  font-family: 'Amatic SC', cursive;
}
.block{
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  font-size: 16px;
}
.block h2{
  position: relative;
  display: block;
  text-align: center;
  margin: 0;
  top: 50%;
  transform: translateY(-50%);
  font-size: 10vw;
  color: white;
  font-weight: 400;
}
.img-parallax {
  width: 100vmax;
  z-index: -1;
  position: absolute;
  top: 0;
  left: 50%;
  transform: translate(-50%,0);
  pointer-events: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="block">
  <img src="https://unsplash.it/1920/1920/?image=1005" data-speed="-1" class="img-parallax">
  <h2>Parallax Speed -1</h2>
</div>
<div class="block">
  <img src="https://unsplash.it/1920/1920/?image=1067" data-speed="1" class="img-parallax">
  <h2>Parallax Speed 1</h2>
</div>
<div class="block">
  <img src="https://unsplash.it/1920/1920/?gravity=center" data-speed="-0.25" class="img-parallax">
  <h2>Parallax Speed -0.25</h2>
</div>
<div class="block">
  <img src="https://unsplash.it/1920/1920/?image=1080" data-speed="0.25" class="img-parallax">
  <h2>Parallax Speed 0.25</h2>
</div>
<div class="block">
  <img src="https://unsplash.it/1920/1920/?random" data-speed="-0.75" class="img-parallax">
  <h2>Parallax Speed -0.75</h2>
</div>
<div class="block">
  <img src="https://unsplash.it/1920/1920/?blur" data-speed="0.75" class="img-parallax">
  <h2>Parallax Speed 0.75</h2>
</div>

Ответ 4

Итак, это рабочий пример, который был одобрен Nishant Solanki, и он должен работать во всех браузерах

function myFunction() {
	speed = 0; 
  speed2 = -1;
  /**
  @ speed
  positive: moves up faster than background
  0: scrolls same as background
  negative: moves down faster
  -1: same as position: fixed
  try different ones to see it in action and you should figure it out
  
  P.S.
  you can apply different speeds to multiple alements to achieve what ever you desire
  */
	y = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
  cont = document.getElementById("prl");
  cont.style.top = (0 - Math.round(y * speed)) +"px";
  img = document.getElementById("image");
  img.style.top = (0 - Math.round(y * speed2)) +"px";
}
*{
  margin: 0;
  padding: 0;
}

#image {
  width: 100%;
  position: relative;
}
#prl {
  position: relative;
  background-color: white;
}
<body onscroll="myFunction()">

  <img src="http://placehold.it/350X225" id="image">

<div id="prl">
  <p>
  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsad
  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksdghjlsadv  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsad
  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksdghjlsadv  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsad
  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksdghjlsadv  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsad
  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksdghjlsadv
  </p>
</div>
</body>

Ответ 5

Не можете ли вы просто использовать что-то так же просто, как $(window).scroll, чтобы обнаружить прокрутку окна, а затем просто .addClass .removeClass или .toggleClass. Затем с новыми стилями, прикрепленными к прокрутке, просто измените положение своего img элемент?

$(document).ready(function(){
    $(window).scroll(function(){
        $('img').toggleClass('scrolled'); 
    })
})

.scrolled { 
  position: absolute;
  z-index: 777; // find correct value to use
  top: 102px; // adjust to customization
  left: 3px; // adjust to customization
}

Примечание://. Более чистая практика заключается в создании этого эффекта с изображением background и настройке его положения с помощью .scroll. Если у вас есть возможность переписать какой-то код для достижения этого, это может стоить того, что долгое время. Если нет, вы можете использовать jQuery .scroll и .toggleClass с настройкой свойства z-index: и position:. Вы должны использовать чистый CSS3 для гибких макетов; если свойство position: не работает, тогда есть конфликт где-то еще с вероятным слишком большим количеством CSS или JS для соответствующих элементов.

Ответ 6

Попробуйте избежать fixed и absolute в css. Надеюсь, вы сочтете это освобождением.

function myFunction() {
  fixIt = document.getElementById('project-image');
  fixIt.style.top = 2 * Math.round(document.body.scrollTop) + "px";
}
* {
  margin: 0;
  padding: 0;
}

#project-image {
  width: 100%;
  position: relative;
}

.project-description,
.project-details>h1 {
  position: relative;
  z-index: 1;
  background: white;
}

.project-details {
  overflow: hidden
}
<body onscroll="myFunction()">


  <div class="project-details">
    <div id="project-image">
      <img src="http://placehold.it/350X225" class="img-responsive">
    </div>
    <h1>
      Project Title
    </h1>
    <p class="project-description">
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
      survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.
      <br/>
      <br/> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
      book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently
      with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
      <br/>
      <br/> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
      book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently
      with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>
  </div>
</body>