【问题标题】:Positioning of element with JS transform properties (CSS get's overwritten by JS)使用 JS 转换属性定位元素(CSS get 被 JS 覆盖)
【发布时间】:2021-12-01 20:49:31
【问题描述】:

我正在尝试将两张图像放在彼此的顶部,并让其中一张在滚动时旋转,而另一张不旋转 - 这很有效,但我无法在我的 CSS 中定位和缩放我的元素。一旦我开始滚动,带有 JS 的图像就会跳到角落,而另一个则保持原位。我相信这是因为我的 JS 覆盖了我的 CSS 属性,但是有没有办法解决这个问题?我可以在维护我的 JS 的同时定位我的两个元素吗?

var elem = document.getElementById("rotatelogo");
window.addEventListener('scroll', function() {
    var value = window.scrollY * 0.25;
    elem.style.transform = `translatex(-50%) translatey(-50%) rotate(${value}deg)`; 
});
body {
  height: 200vh;
  background: darkblue;
}

.guide {
  width:150px;
  height:150px;
  margin-top:50px;
  margin-bottom:-300px;
  margin-left:50px;
}
<div class="guide" style="position:relative">
    <img src="http://jakobnatorp.com/wp-content/uploads/2021/10/ARROW.png" style="position:fixed;"/>
    <img class="portfolio" id="rotatelogo" src="http://jakobnatorp.com/wp-content/uploads/2021/10/SELECTED-WORK-BEIGE.png" style="position:fixed"/>
</div>

【问题讨论】:

  • 我创建了一个正在运行的Stack Snippet。如有任何错误,请随时编辑。

标签: javascript css scroll position css-position


【解决方案1】:

我不确定你想通过使用translatex(-50%) translatey(-50%) 来实现什么,但这会导致图像中心位于父元素的左上角。 如果您只使用elem.style.transform = `rotate(${value}deg)`;,它将原地旋转。

【讨论】:

    【解决方案2】:

    从您的代码中删除翻译。

    var elem = document.getElementById("rotatelogo");
    window.addEventListener('scroll', function() {
        var value = window.scrollY * 0.25;
        elem.style.transform = `rotate(${value}deg)`; 
    });
    body {
      height: 200vh;
      background: darkblue;
    }
    
    .guide {
      width:150px;
      height:150px;
      margin-top:50px;
      margin-bottom:-300px;
      margin-left:50px;
    }
    <div class="guide" style="position:relative">
        <img src="http://jakobnatorp.com/wp-content/uploads/2021/10/ARROW.png" style="position:fixed;"/>
        <img class="portfolio" id="rotatelogo" src="http://jakobnatorp.com/wp-content/uploads/2021/10/SELECTED-WORK-BEIGE.png" style="position:fixed"/>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-22
      • 2011-05-03
      • 1970-01-01
      • 1970-01-01
      • 2011-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多