【问题标题】:Apply "live" css with jquery to many tags with same class indepedently将带有 jquery 的“live” css 独立应用于许多具有相同类的标签
【发布时间】:2021-03-06 12:01:39
【问题描述】:

我的舞台上有 8 个学生,它们与鼠标光标交互移动。我不知道如何将css独立应用于每个。有人可以帮我解决这个问题吗?

这是代码

jQuery(function($){

    /*I have 8 pupils in total*/
    $("body").mousemove(function(event) {
        var eye = $(".pupil");
        var x = (eye.offset().left) + (eye.width() / 2);
        var y = (eye.offset().top) + (eye.height() / 2);
        var rad = Math.atan2(event.pageX - x, event.pageY - y);
        var rot = (rad * (180 / Math.PI) * -1) + 180;
        

        /*I can't figure out how to fix the -for each-*/
        $(eye).each(function() {
            $(this).css({ 'transform': 'rotate(' + rot + 'deg)'});
        });

    });
});

这里是 jsFiddle:https://jsfiddle.net/NickBil/qaspfk1L/2/

【问题讨论】:

  • $(".pupil") 是一个数组,你应该遍历它。这会有所帮助:api.jquery.com/jquery.each
  • 谢谢,会好好看看这个。

标签: jquery css rotation each mousemove


【解决方案1】:

使用 jquery 有助于在集合或列表的基础上进行思考。你的直觉是正确的,但你应用它有点不正确。所以不是

jQuery(function($){

  /*I have 8 pupils in total*/
  $("body").mousemove(function(event) {
    var eye = $(".pupil");
    var x = (eye.offset().left) + (eye.width() / 2);
    var y = (eye.offset().top) + (eye.height() / 2);
    var rad = Math.atan2(event.pageX - x, event.pageY - y);
    var rot = (rad * (180 / Math.PI) * -1) + 180;


    /*I can't understand how to fix the -for each-*/
    $(eye).each(function() {
      $(this).css({ 'transform': 'rotate(' + rot + 'deg)'});
    });

  });
});

尝试更多这样的

jQuery(function($){

        /*I have 8 pupils in total*/
        $("body").mousemove(function(event) {
        
            $(".pupil").each(function() {
              var eye = $(this);
              var x = (eye.offset().left) + (eye.width() / 2);
              var y = (eye.offset().top) + (eye.height() / 2);
              var rad = Math.atan2(event.pageX - x, event.pageY - y);
              var rot = (rad * (180 / Math.PI) * -1) + 180;
            
              $(this).css({ 'transform': 'rotate(' + rot + 'deg)'});

        });
    });    
});

【讨论】:

  • 非常感谢,我现在明白这个方法了:)
猜你喜欢
  • 1970-01-01
  • 2021-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-05
  • 1970-01-01
  • 2021-09-09
  • 1970-01-01
相关资源
最近更新 更多