【问题标题】:Best way to move an element around (performance wise)移动元素的最佳方式(性能方面)
【发布时间】:2014-02-25 21:41:45
【问题描述】:

我需要水平移动一个 DOM 元素。拖动从 mousedown 开始,在 mousemove 移动并在 mouseup

结束

所有这些都需要在一个拥有大量动画和内容的网站上进行,因此性能至关重要。就我现在所拥有的,我确实看到了一些延迟;元素在鼠标移动之后移动一点。只是这样看起来很难看。

所以,基本上我有以下内容:

var offset = 0, startX;
$('.draggable').on('mousedown', function (e) {
        startX = e.pageX;
    })
    .on('mouseup', function() {
        startX = null;
    })
    .on('mousemove', function (e) {
        if(startX) {
           newX = e.pageX;
           offset += newX - startX;
           startX = newX;
           this.style['-webkit-transform'] = 'translate(' + offset + 'px)';
        }
    });

(jsfiddle)

我想知道对这段代码进行哪些更改可以提高性能?

更新:比如requestAnimationFrame和FPS,有什么帮助吗?

【问题讨论】:

  • 我会先删除 jquery。
  • 是的,虽然我怀疑在这种情况下我只使用它来绑定事件它并不重要
  • 我怀疑你的怀疑是正确的。特别是因为您关心性能。甚至 2.0 也可以规范您可能不需要的东西。 github.com/jquery/jquery/blob/2.1.0-rc1/src/event.js
  • 考虑到您要求的是性能最高的方式,并且您只针对 webkit,包括 jquery,因为您想要做的是“非常愚蠢”恕我直言。

标签: javascript performance css transform


【解决方案1】:

不是很大的改进,但你可以写:

var offset = 0, startX;
$('.draggable').on('mousedown', function (e) {
        startX = e.pageX - offset;
    })
    .on('mouseup', function() {
        startX = null;
    })
    .on('mousemove', function (e) {
        if(startX) {
           offset = e.pageX - startX;
           this.style['-webkit-transform'] = 'translate(' + offset + 'px)';
        }
    });

fiddle

【讨论】:

  • 感谢改进,它至少向前迈出了一步!
猜你喜欢
  • 2022-08-13
  • 1970-01-01
  • 2019-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-16
  • 2021-05-26
相关资源
最近更新 更多