微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在页面滚动时以 -90 度旋转图像

如何解决在页面滚动时以 -90 度旋转图像

我想让我的图像在页面滚动时以 -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)";
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。