我正在网络上试验“滚动”事件监听器,以便为我的元素添加一些运动设计。在这个测试元素中,我有一个 div 元素对用户滚动页面使用react。
我的带有元素和脚本的 html 代码:
<div id="top_div" class="normal_height"></div>
<script src="js/scroll_top_element.js"></script>
在 css 中,我在两个类之间切换,以通过某个“点击”点调整 div 元素的高度。
.adapt_height{
height: 10vh;
}
.normal_height{
height: 25vh;
}
我的 Javascript 代码如下:我使用去抖功能过滤掉过多的 UI 线程输入并提高应用程序的整体性能。
function debounce(func, wait=10, immediate = true){
var timeout;
//debounce is a higher order function and will return another function
return function run_code() {
var context = this;
//arguments is local variable of a function, refers to all arguments
var args = arguments;
//variable later is a function
var later = function(){
timeout = null;
//if it is not time zero, apply checkSlide function
if(!immediate) func.apply(context, args);
};
var Callnow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if(Callnow) func.apply(context, args);
}
}
下一个函数监听屏幕上的滚动,应该做两件事。第一件事是当用户滚动经过设置为 50 的 y 标记时立即调整元素高度。此功能正常。
它应该做的第二件事是,当滚动经过“点击点 y”时,使元素的高度线性适应窗口的滚动属性。我尝试使用“element.style.height”,然后添加“scrollY”属性以使其随着屏幕上的滚动而展开。但这不起作用。由于某种原因我无法将它们加起来..
window.addEventListener('scroll', debounce(function(){
var y = window.scrollY;
console.log(y);
if (y < 50){
document.getElementById("top_div").className = "adapt_height";
console.log(document.getElementById("top_div").className);
}
else {
document.getElementById("top_div").className = "normal_height";
document.getElementById("top_div").style.height += y;
console.log(document.getElementById("top_div").clientHeight);
}
}));
有什么建议吗?
最佳答案
- 将
getElementById
移出函数。使用变量来存储元素引用。每 10 毫秒搜索一次 DOM 会占用大量资源。 .style.height
不返回元素高度,使用.clientHeight
代替。但同样,从 DOM 读取是资源密集型的。可能您可以在不知道实际元素高度的情况下计算新高度。.style.height += y
您必须使用 css 单位设置值,例如10px
而不是10
关于javascript - 滚动位置决定元素高度 - Web 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56552621/