启用/禁用鼠标移动功能

问题描述 投票:0回答:1

我有两个按钮。当我单击第一个按钮时,我的“d”和“bg”元素会随着鼠标移动而移动。

<section>
    <div class="d"></div>
    <div class="bg"></div>
</section>
<div class="button1"></div>
<div class="button2"></div>


$('.button1').click(function(){
    $('section').delay(2500).mousemove(function(e) {
        parallaxIt(e, ".d", -12.5);
        parallaxIt(e, ".bg", -3.75);
    });
});

function parallaxIt(e, target, movement) {
    var $this = $('section');
    var relX = e.pageX - $this.offset().left;
    var relY = e.pageY - $this.offset().top;

    TweenMax.to(target, 1, {
        x: (relX - $this.width() / 2) / $this.width() * movement,
        y: (relY - $this.height() / 2) / $this.height() * movement
    });
}

我希望当我单击第二个按钮时,元素不再移动。

我先尝试了解除绑定的方法:

$('.button2').click(function(){
    $('section').unbind('mousemove');
});

这样,我的问题是,当鼠标移动停止时,我的元素不会在原来的位置完成,而是突然停留在停止时的位置。 不知何故,如果有适合我的方法,我更喜欢这种方法。

第二种方法是关闭方法:

$('.button2').click(function(){
    $('section').mousemove(function() {
        $('.d, .bg').off("mousemove", mouse);
    });
});

我的问题是单击后它根本不会停止鼠标移动。

也许知道我使用 jQuery v1.11.0 很重要。请给我一个简单的答案,因为我做网页设计是出于爱好,主要是为了我自己的个人网站或给朋友,所以我不专业。

javascript jquery mousemove
1个回答
0
投票
// Initialize a variable to track whether the mousemove effect is active
var isMousemoveActive = false;

// Function to reset the elements' positions to their original state
function resetPositions() {
  // Use TweenMax to smoothly reset positions
  TweenMax.to(".d, .bg", 1, { x: 0, y: 0 });
}

// Button 1 click handler
$('.button1').click(function () {
  // Start the mousemove effect
  isMousemoveActive = true;

  // Attach the mousemove event to the section
  $('section').mousemove(function (e) {
    if (isMousemoveActive) {
      // Apply parallax effect
      parallaxIt(e, ".d", -12.5);
      parallaxIt(e, ".bg", -3.75);
    }
  });
});

// Button 2 click handler
$('.button2').click(function () {
  // Stop the mousemove effect
  isMousemoveActive = false;

  // Detach the mousemove event from the section
  $('section').off('mousemove');

  // Reset the positions of .d and .bg elements
  resetPositions();
});

// Function to apply parallax effect
function parallaxIt(e, target, movement) {
  var $this = $('section');
  var relX = e.pageX - $this.offset().left;
  var relY = e.pageY - $this.offset().top;

  // Use TweenMax to smoothly apply the parallax effect
  TweenMax.to(target, 1, {
    x: (relX - $this.width() / 2) / $this.width() * movement,
    y: (relY - $this.height() / 2) / $this.height() * movement,
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.