【发布时间】:2019-10-10 21:54:49
【问题描述】:
我正在尝试在滚动时更改 div 的大小(或比例)。 这个 div 有一个 0.8 的比例附在它的 css 上。我想在滚动时逐渐达到 1 的比例。 IntersectionObserver 似乎是一个不错的选择,而不是滚动事件,但我不知道我是否可以使用它来更改元素的状态。
【问题讨论】:
标签: javascript scroll intersection-observer
我正在尝试在滚动时更改 div 的大小(或比例)。 这个 div 有一个 0.8 的比例附在它的 css 上。我想在滚动时逐渐达到 1 的比例。 IntersectionObserver 似乎是一个不错的选择,而不是滚动事件,但我不知道我是否可以使用它来更改元素的状态。
【问题讨论】:
标签: javascript scroll intersection-observer
您可以使用更改 div 的比例。
document.getElementById("scaledDiv").style.transform = "scale(1)";
滚动事件应该做你想做的事。您可以继续添加更多 if 语句并检查它们滚动了多少像素,以便在它们向上滚动时逐渐将其更改为 1 甚至回到 0.8。下面的 50 代表距离页面顶部 50 个像素。
window.onscroll = function() {
if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
// They are scrolling past a certain position
document.getElementById("scaledDiv").style.transform = "scale(1)";
} else {
// They are scrolling back
}
};
【讨论】:
希望对你有帮助:
const container = document.querySelector('.container');
const containerHeight = container.scrollHeight;
const iWillExpand = document.querySelector('.iWillExpand');
container.onscroll = function(e) {
iWillExpand.style.transform = `scale(${0.8 + 0.2 * container.scrollTop / (containerHeight - 300)})`;
};
.container {
height: 300px;
width: 100%;
overflow-y: scroll;
}
.scrollMe {
height: 1500px;
width: 100%;
}
.iWillExpand {
position: fixed;
width: 200px;
height: 200px;
top: 10px;
left: 10px;
background-color: aqua;
transform: scale(0.8);
}
<div class='container'>
<div class='scrollMe' />
<div class='iWillExpand' />
</div>
【讨论】: