问题描述
我想让我的图像在页面滚动时以 -90 度旋转并坚持使用 -90 度,直到我到达我的网站底部。但是如果我再次上升并到达顶部,它应该会旋转回正常(0 度)。
有人能帮我解决这个问题吗?
最好的, 莱昂
解决方法
我不确定这是需要的解决方案,但它有效:
HTML
<img id="the_image" src="./smile.png">
CSS
#the_image {
position: fixed;
top: 10px;
left: 10px;
transform-origin: 50% 50%;
transform: rotate(0deg);
}
JS
//get window height
const b_height = document.querySelector("body").offsetHeight;
//get the image
const image = document.getElementById("the_image");
//set maximum rotation value
const maxRotate = -90;
//add listenet on scroll
window.addEventListener("scroll",function (e) {
//calculating the rotation value
let rotation = (window.scrollY / (b_height - window.innerHeight)) * maxRotate;
rotation = rotation < maxRotate ? maxRotate : rotation;
//use the value you get
image.style.transform = "rotate(" + rotation + "deg)";
});