javascript - 如何使代码中高度的像素值动态化?
问题描述
我已经构建了一个小脚本,让选择的对象在用户向下滚动时淡入。我的问题是这个脚本是相当静态的。如果我将它应用于 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>
解决方案
这将检查元素是否对用户可见,如果是则添加类,如果不是则将其删除。要做到这一点,您只需要将 应用于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>
推荐阅读
- android - 是否可以在返回 LiveData 的 Room @DAO 中编写“挂起”函数?
- android - 如何在 xml 中编辑最上面导航栏的颜色?
- python-3.x - 检查点文件的加载方式/位置
- c++ - QQmlEngine retranslate not translating other StackView items
- apache-spark - 不支持重新分区后合并
- java - 片段中的自定义ListView,我需要什么文件?
- typescript - 对类型转换为 TypeScript 类型的变量调用`new`
- python - QTreeView 数据更改信号/插槽实现?
- amazon-web-services - AWS Lambda / API Gateway 不通过编码
- javascript - 如何从 Google Speech to Text API 获得有效响应?