javascript - 我可以使用 javascript 滚动事件更改 div 的宽度和高度吗?
问题描述
我的 div 覆盖了整个屏幕,即 div 的宽度和高度为 100%。我想要一个滚动事件来减小向上滚动时该 div 的宽度和高度,并在向下滚动时增加该 div 的宽度和高度。可能吗?请在这里帮帮我。如果我在这里添加滚动事件,它可能不起作用,因为滚动不会发生,因为 div 适合整个屏幕。
这是我的代码
<html>
<head>
<script src="myscript.js"></script>
</head>
<body onload="myfunc()">
<div class="firstdiv">
</div>
</body>
</html>
function myfunc(){
var x = document.getElementsByClassName("firstdiv");
console.dir(x);
x[0].style.width = "100%";
x[0].style.height = "100%";
x[0].style.background = "red";
x[0].style.position = "relative";
x[0].style.top = "0";
x[0].style.left = "0";
}
解决方案
我希望这可以帮助你
<body style="overflow: scroll; height: 1000px;" onload="scrollDetect()">
<div class="firstdiv" style="border:1px solid black; margin: 0 auto; width: 200px;height: 200px;">
</div>
<script>
function scrollDetect() {
let div = document.querySelector('.firstdiv')
var lastScroll = 0;
window.onscroll = function () {
let currentScroll = document.documentElement.scrollTop; // Get Current Scroll Value
if (currentScroll > 0 && lastScroll <= currentScroll) {
lastScroll = currentScroll;
div.style.width = '50%'
div.style.height = "50%";
div.style.background = "red";
div.style.position = "relative";
div.style.top = "0";
div.style.left = "0";
} else {
lastScroll = currentScroll;
div.style.width = '200px'
div.style.height = '200px'
}
};
}
</script>
</body>
推荐阅读
- c# - 根据 ComboBox 选择更改 GroupBox 的内容
- c# - ABP 实时通知系统后台作业
- pandas - Pandas update() 运行时间很长
- javascript - localStorage:我无法使用 @ngx-pwa/local-storage 删除项目
- python - SQLAlchemy 没有提交更新
- javascript - D3.js 刻度格式:显示月份变化时
- sql - RDBMS:计算并打印返回日期、返回月份和返回年份
- java - Spring HATEOAS 不尊重资源链接的默认包含属性
- python - python pandas将总和列转换为总和列
- android - 输入类型 = 注册号