首页 > 解决方案 > 使用JS旋转图像时如何添加边距顶部

问题描述

当图像旋转 90 度时,我想在图像顶部添加边距。这就是我旋转图像的方式:

const img = document.querySelector("#mocci-logo")

document.addEventListener("scroll", (e) => {
  if(!window.scrollY) {
    img.style.transform = "rotate(0deg)"
  } else {
    img.style.transform = "rotate(-90deg)"
  }
})

我知道这可能很简单,但我是初学者。所以希望有人能告诉我如何做到这一点。谢谢!

标签: javascriptjquerycssfunctionmargin

解决方案


试试这个:

const img = document.querySelector("#mocci-logo")

document.addEventListener("scroll", (e) => {
  if(!window.scrollY) {
    img.style.transform = "rotate(0deg)"
    img.style.marginTop = "0px"; // This can also be 0 or "0".
  } else {
    img.style.transform = "rotate(-90deg)"
    img.style.marginTop = "60px";
  }
})

推荐阅读