Проблема с мышью при использовании jquery fadeIn

#javascript #jquery #css

#javascript #jquery ( jquery ) #css — код

Вопрос:

Я пытаюсь, чтобы этот круг следовал за курсором. Однако мне нужно, чтобы курсор исчезал после того, как пользователь нажимает кнопку, когда это происходит, хотя круг не будет центрирован на курсоре.

Первый фрагмент кода показывает желаемый результат в терминах круга, правильно следующего за курсором и центрированного.Второй фрагмент показывает желаемое затухание при нажатии кнопки, но, как вы можете видеть, круг не будет центрирован на курсоре

Первый фрагмент кода:

 const cursor = document.querySelector('.test');
const {
  width,
  height
} = cursor.getBoundingClientRect();
document.addEventListener('mousemove', e => {
  cursor.style.top = e.y - height / 2   'px';
  cursor.style.left = e.x - width / 2   'px';
}); 
 .test {
    position: absolute;
    width: 25rem;
    height: 25rem;
    border-radius: 50%;
    background-color: red;
    z-index: 200;
} 
 <div class="test"></div> 

Второй фрагмент кода:

 $("#myBtn").click(function(){
  $('.test').fadeIn();
}); 

const cursor = document.querySelector('.test');
const {
  width,
  height
} = cursor.getBoundingClientRect();
document.addEventListener('mousemove', e => {
  cursor.style.top = e.y - height / 2   'px';
  cursor.style.left = e.x - width / 2   'px';
}); 
 .test {
    position: absolute;
    width: 25rem;
    height: 25rem;
    border-radius: 50%;
    background-color: blue;
    z-index: 200;
    display: none;
} 
 <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<button id="myBtn">show</button>

<div class="test"></div> 

Ответ №1:

Во втором примере, на странице init у .test div есть display: none , так что его height и width есть 0 . Вы должны вычислить их после fadeIn , чтобы получить правильный результат.

Вы также можете добавить mousemove прослушиватель после fadeIn :

 $("#myBtn").click(function() {
  $('.test').fadeIn('slow', function() {
    const cursor = document.querySelector('.test')
    , { width, height } = cursor.getBoundingClientRect();
    
    document.addEventListener('mousemove', e => {
      cursor.style.top = e.y - height / 2   'px';
      cursor.style.left = e.x - width / 2   'px';
    });
  });
}); 
 .test {
  position: absolute;
  width: 25rem;
  height: 25rem;
  border-radius: 50%;
  background-color: blue;
  z-index: 200;
  display: none;
} 
 <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<button id="myBtn">show</button>

<div class="test"></div> 

Ответ №2:

Другой, возможно, более простой альтернативой является просто вызов fadeOut() (с длительностью 0) в .test div при загрузке страницы вместо использования display:none

 $("#myBtn").click(function(){
  $('.test').fadeIn();
}); 

const cursor = document.querySelector('.test');
const {
  width,
  height
} = cursor.getBoundingClientRect();

$('.test').fadeOut(0);

document.addEventListener('mousemove', e => {
  cursor.style.top = e.y - height / 2   'px';
  cursor.style.left = e.x - width / 2   'px';
}); 
 .test {
    position: absolute;
    width: 25rem;
    height: 25rem;
    border-radius: 50%;
    background-color: blue;
} 
 <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<button id="myBtn">show</button>

<div class="test"></div>