【问题标题】:Rotate an element on scroll, what is the lightest way?在滚动上旋转元素,最轻的方法是什么?
【发布时间】:2016-08-13 04:44:24
【问题描述】:

在我实习时制作的网站上,我想制作一个箭头,一旦用户向下滚动,它就会变平。我试过用 jQuery 来做这个,但这对浏览器来说似乎很重。

对于这个函数,我使用了 .scroll() 函数,以及在用户向下滚动时使箭头(三角形)变平的计算:

$(window).scroll(function(e){
     triangleRotation = 5.6125 - ($(window).scrollTop() / ($(window).height() / 7.3));
       if (triangleRotation <= 0) {
        triangleRotation = 0;
       }
       $('.triangle-left').css({'transform': 'rotate(' + triangleRotation + 'deg)', '-webkit-transform': 'rotate(' + triangleRotation + 'deg)', '-moz-transform': 'rotate(' + triangleRotation + 'deg)'});
       $('.triangle-right').css({'transform': 'rotate(-' + triangleRotation + 'deg)', '-webkit-transform': 'rotate(-' + triangleRotation + 'deg)', '-moz-transform': 'rotate(-' + triangleRotation + 'deg)'});
});

我还通过三角形图像进行了尝试,并简单地将图像展平。这也太重了。

有没有更简单的方法来做到这一点?

【问题讨论】:

  • 我建议始终使用 css 转换,因为这只会触发绘制,而不会触发重排或布局。 - 另外,请确保在 onscroll 事件函数上使用“节流”。
  • 这是通过css转换完成的,我只是发布了源代码
  • 可能不会在每次触发滚动事件时计算$(window).height() / 7.3。 - Here is an example of a js throttle
  • 但是,我应该如何旋转三角形(如果用户停止滚动则让旋转停止)
  • 另一个建议,将三角形对象“缓存”在滚动函数之外的变量中。您的代码当前在滚动时旋转三角形,当用户停止滚动时,旋转也会停止...

标签: javascript jquery rotation transform


【解决方案1】:

你可以尝试:

  • 创建一个全局可访问变量“is_scrolling”,并在滚动事件中将其设置为 true(如果不是 true)。
  • 如果用户停止滚动,请使用 here 中的代码将变量设置为 false
  • 使用 setTimeout 进行旋转。您可以使用超时时间和每步的度数(如果旋转与滚动位置无关)来管理速度,否则请使用您的计算。

优点是,这与滚动事件分离。您无法控制触发滚动事件的频率,但您可以控制触发 setTimeout 中的函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-25
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    • 2012-10-14
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多