首页 > 解决方案 > 如何使代码中高度的像素值动态化?

问题描述

我已经构建了一个小脚本,让选择的对象在用户向下滚动时淡入。我的问题是这个脚本是相当静态的。如果我将它应用于 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>

标签: javascriptjqueryhtmlcssweb

解决方案


这将检查元素是否对用户可见,如果是则添加类,如果不是则将其删除。要做到这一点,您只需要将 应用于class header-js-scroll-fade您想要的任何元素。

函数 isInViewport 来自用户 Tom Paž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>


推荐阅读