【问题标题】:Move elements independently js独立移动元素js
【发布时间】:2017-02-01 12:28:22
【问题描述】:

我正在尝试为不同的箭头设置动画以指向光标,但我找不到一个轻量级的解决方案。

我正在使用下面的代码,但它对网站来说似乎有点重。有没有办法优化代码?

干杯! T

// the same as yours.
  function rotateOnMouse(e, pw) {
      var offset = pw.offset();
      var center_x = (offset.left) + ($(pw).width() / 2);
      var center_y = (offset.top) + ($(pw).height() / 2);
      var mouse_x = e.pageX;
      var mouse_y = e.pageY;
      var radians = Math.atan2(mouse_x - center_x, mouse_y - center_y);
      var degree = (radians * (180 / Math.PI) * -1);
      $(pw).css('-moz-transform', 'rotate(' + degree + 'deg)');
      $(pw).css('-webkit-transform', 'rotate(' + degree + 'deg)');
      $(pw).css('-o-transform', 'rotate(' + degree + 'deg)');
      $(pw).css('-ms-transform', 'rotate(' + degree + 'deg)');
  }

  $(document).mousemove(function(e) {

    $(document).bind('mousemove.rotateImg', function(e2) {
      rotateOnMouse(e2, $('#arrowD1'));
    });
    $(document).bind('mousemove.rotateImg', function(e2) {
      rotateOnMouse(e2, $('#arrowD2'));
    });
    $(document).bind('mousemove.rotateImg', function(e2) {
      rotateOnMouse(e2, $('#arrowD3'));
    });
    $(document).bind('mousemove.rotateImg', function(e2) {
      rotateOnMouse(e2, $('#arrowD4'));
    });
    $(document).bind('mousemove.rotateImg', function(e2) {
      rotateOnMouse(e2, $('#arrowD5'));
    });
    $(document).bind('mousemove.rotateImg', function(e2) {
      rotateOnMouse(e2, $('#arrowD6'));
    });


  });

http://codepen.io/thalesribeiro/pen/egVgpp

【问题讨论】:

    标签: javascript jquery css jquery-animate


    【解决方案1】:

    我有一些想法可以帮助提高性能:

    • 在改变变换时使用 requestAnimationFrame
    • 将箭头节点存储在一个变量中,这样浏览器就不必在每次鼠标移动时都查询它们,这将大大提高性能
    • 您正在添加多个事件侦听器,只需一个即可实现相同的效果
    • bind() 已弃用 on()

    var arrow1 = $('#arrowD1');
    var arrow2 = $('#arrowD2');
    $(document).on('mousemove', function(e){
        rotateOnMouse(e, arrow1);
        rotateOnMouse(e, arrow2);
    );

    没有测试代码,但它应该让你知道它应该是什么样子。

    编辑:

    Codepen 和我的建议:codepen

    【讨论】:

    • 嗯,它对我不起作用。您能否向我展示它如何与其余代码一起应用的示例?
    • 我根据我的建议编辑了您的 codepen,添加了回答链接。另外,如果您想进一步提高性能,我建议使用 jquery 尚不支持的被动事件侦听器
    • 如果我想用同一个类调用所有元素,它会如何工作?例如 .arrows 然后我不必为每个箭头调用相同的函数?
    • 如果你这样做,你仍然需要遍历每个箭头来单独计算旋转
    • 你有我会怎么做的例子吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多