如何绑定/调用/传递'this'到mousemove函数

时间:2018-03-06 00:25:24

标签: javascript

我正在努力{card}元素mousedown,然后使用mousemove移动该卡片。

我的变量位于顶部,后跟函数,接着是事件监听器:

// variables


// selector for elements with class .card
var cards = document.querySelectorAll('.card');

// variable containing x and y coordinates of mouse
var mousePosition;

// boolean to track if mouse is down
var isDown = false;



// functions


// function for mousedown on .card
function cardHold() {

  // set isDown to true
  isDown = true;

  this.style.boxShadow = '0 14px 28px rgba(0,0,0,0.25), 0 10px 10px rgba(0,0,0,0.22)';

 }


// function for mouseup on .card
function cardRelease() {

  // set isDown to false
  isDown = false;

  this.style.boxShadow = '0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23)';

}

// function for mousedown & move on .card
function mouseMove() {

  if (isDown) {

    mousePosition = {

      x : event.clientX,
      y : event.clientY

    };

    // this.style.left = (mousePosition.x + 'px');
    // this.style.top  = (mousePosition.y + 'px');

  }

}


// event listeners

// loop through elements with class .card and attach event listeners for mousedown and mouseup
for (var index = 0; index < cards.length; index++) {

  cards[index].addEventListener('mousedown', cardHold);
  cards[index].addEventListener('mouseup', cardRelease);

}

// attach an event listener on the document to track mousemove
document.addEventListener('mousemove', mouseMove);

thiscardHold函数中cardRelease的使用情况正常,但thismouseMove的使用情况有误。

最底线的事件监听器调用mouseMove函数:

document.addEventListener('mousemove', mouseMove);

mouseMove函数中,我尝试了这个:

    // this.style.left = (mousePosition.x + 'px');
    // this.style.top  = (mousePosition.y + 'px');

..这是我尝试通过重新定位this来移动卡片的地方,但是mouseMove正在document对象传递this这里,我通过检查实现console.log(this)函数中的mouseMove

我想我需要在这里使用bindapplycall以某种方式将this函数从cardHold函数传递给{{1}函数,但我无法在这里找出正确的语法,或者使用这三个中的哪一个。

类似的东西:

mouseMove

...在this.bind(mouseMove); 函数的开头,但这似乎不正确。

1 个答案:

答案 0 :(得分:0)

我最终创建了一个变量来存储this函数中的cardHold

function cardHold() {

  // store this within variable
  movingCard = this;

  // set isDown to true
  isDown = true;
  console.log(isDown);

  this.style.boxShadow = '0 14px 28px rgba(0,0,0,0.25), 0 10px 10px rgba(0,0,0,0.22)';

}

然后我可以访问movingCard并在mouseMove函数中移动它:

// function for mousedown & move on .card
function mouseMove() {

  if (isDown) {

    mousePosition = {

          x : event.clientX,
          y : event.clientY

      };

       movingCard.style.left = (mousePosition.x) + 'px';
       movingCard.style.top  = (mousePosition.y) + 'px';

  }

}

虽然这似乎有效,但我觉得必须有一个更好的解决方案,并且如果他们可以提供帮助,就会标记别人的答案。