来自div更改元素属性的光标接近度

时间:2019-04-26 15:35:34

标签: javascript jquery

此代码对于带有 .trigger-element类的第一个元素非常有效。问题是当我尝试影响同一类的其他元素时,它不起作用。

我尝试添加forEach方法,但无法使其正常工作。

它一次只能影响一个元素,并且应该对每个div有效。 https://jsfiddle.net/secondleft/53mk1dst/6/

(function() {
  var mX, mY, distance,
    $element = $('.trigger-element');

  // proximity threshold
  var proximity = 300;

  function calculateDistance(elem, mouseX, mouseY) {
    return Math.floor(
      Math.sqrt(
        Math.pow(mouseX - (elem.offset().left + (elem.width() / 2)), 2) +
        Math.pow(mouseY - (elem.offset().top + (elem.height() / 2)), 2)
      )
    ) - Math.round(elem.width() / 2);
  }

  $(document).mousemove(function(e) {
    mX = e.pageX;
    mY = e.pageY;
    distance = calculateDistance($element, mX, mY);

    if (distance < proximity) {
      $element.addClass("triggered");
    } else {
      $element.removeClass("triggered");
    }
  });

})();
body {
  background: black;
}

.trigger-element {
  height: 40px;
  width: 80px;
  border: 1px solid #16f9f9;
  margin: 20px;
}

.triggered {
  color: #05080a;
  background: #16f9f9;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="trigger-element"></div>
<div class="trigger-element" style="position:absolute;right:0;"></div>

1 个答案:

答案 0 :(得分:0)

您需要在此处添加循环:

  $(document).mousemove(function(e) {
    mX = e.pageX;
    mY = e.pageY;

    $element.each(function(i,el) {
      const $el = $(el);
      distance = calculateDistance($el, mX, mY);

      if (distance < proximity) {
        $el.addClass("triggered");
      } else {
       $el.removeClass("triggered");
      }  
    });


  });