我正在努力{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);
this
和cardHold
函数中cardRelease
的使用情况正常,但this
中mouseMove
的使用情况有误。
最底线的事件监听器调用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
。
我想我需要在这里使用bind
或apply
或call
以某种方式将this
函数从cardHold
函数传递给{{1}函数,但我无法在这里找出正确的语法,或者使用这三个中的哪一个。
类似的东西:
mouseMove
...在this.bind(mouseMove);
函数的开头,但这似乎不正确。
答案 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';
}
}
虽然这似乎有效,但我觉得必须有一个更好的解决方案,并且如果他们可以提供帮助,就会标记别人的答案。