如何使代码中高度的像素值动态变化?

时间:2019-07-27 17:05:42

标签: javascript jquery html css web

我建立了一个小脚本,当用户向下滚动时,所选对象可以淡入。我的问题是此脚本非常静态。例如,如果将其应用于20个不同的对象,则每次都必须设置高度。这是一个示例:

$(document).ready(function () {
  $(window).scroll(function () {
    if ($(this).scrollTop() > 500) {
      $(".header-js-scroll-fade").css({"opacity" : "1"});
      $(".home-vorteile").addClass("header-img-fade-in-by-scroll");
    }
    else {
      $(".header-js-scroll-fade").css({"opacity" : "0"});
      $(".home-vorteile").removeClass("header-img-fade-in-by-scroll");
    }
  });
});
.header-js-scroll-fade {
	opacity: 0;
	transition: 0.5s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h1 id="vorteile-text">Vertrauen durch,</h1>

<section class="home-vorteile">
  <div class="header-js-scroll-fade header-img-fade-in-by-scroll">
    <img src="https://via.placeholder.com/500" />
    <h2>Sicherheit.</h2>
  </div>
  <div class="header-js-scroll-fade header-img-fade-in-by-scroll">
    <img src="https://via.placeholder.com/500" />
    <h2>Neueste KI Technik.</h2>
  </div>
  <div class="header-js-scroll-fade header-img-fade-in-by-scroll">
    <img src="https://via.placeholder.com/500" />
    <h2>Beste Materialien.</h2>
  </div>
</section>

1 个答案:

答案 0 :(得分:0)

这将检查该元素是否对用户可见,如果可以,则添加该类,否则将其删除。为此,您只需将class header-js-scroll-fade应用于所需的任何元素。

isInViewport函数来自用户TomPažourek,位于此处:https://stackoverflow.com/a/40658647/8605830

// https://stackoverflow.com/a/40658647/8605830
$.fn.isInViewport = function() {
    var elementTop = $(this).offset().top;
    var elementBottom = elementTop + $(this).outerHeight();

    var viewportTop = $(window).scrollTop();
    var viewportBottom = viewportTop + $(window).height();

    return elementBottom > viewportTop && elementTop < viewportBottom;
};

$(document).ready(function () {

  $(window).scroll(function () {
  
    $('.header-js-scroll-fade').each(function () {
      if ($(this).isInViewport()) {
        $(this).addClass("visible");
      }
      else {
        $(this).removeClass("visible");
      }
      
    });
    
  });
  
});
.header-js-scroll-fade {
	opacity: 0;
	transition: 0.5s;
}

.header-js-scroll-fade.visible {
	opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h1 id="vorteile-text">Vertrauen durch,</h1>

<section class="home-vorteile">
  <div class="header-js-scroll-fade">
    <img src="https://via.placeholder.com/500" />
    <h2>Sicherheit.</h2>
  </div>
  <div class="header-js-scroll-fade">
    <img src="https://via.placeholder.com/500" />
    <h2>Neueste KI Technik.</h2>
  </div>
  <div class="header-js-scroll-fade">
    <img src="https://via.placeholder.com/500" />
    <h2>Beste Materialien.</h2>
  </div>
</section>