我要用Angular2创建一个可拖动的垂直条。当用户点击它时,isDragging
应设置为true,然后当鼠标移动时应调用moveHandler
。一切看起来都很简单,但是:
ngOnInit
中的if-cond为true,则永远不会打印“拖动”。ngOnInt
中的if-cond为false时,鼠标启动后会打印“拖动”。import {Component, OnInit} from '@angular/core';
@Component({
selector: 'my-app',
template: ` <div id="handler_vertical" (mousedown)="startDragging()"></div> `
})
export class AppComponent implements OnInit {
isDragging = false;
width = 0;
startDragging() {
console.log("start dragging");
this.isDragging = true;
}
dragHanlder(event: MouseEvent) {
if (this.isDragging) {
console.log("dragging");
this.width -= event.movementX;
// console.log("movementX:"+ event.movementX);
}
}
stopDragging() {
console.log("stop dragging");
this.isDragging = false;
}
ngOnInit() {
window.onmouseup = this.stopDragging;
if(false){
window.onmousemove = this.dragHanlder;
}else{
window.onmousemove = (event) => {
console.log("moving");
this.dragHanlder(event);
}
}
}
}
答案 0 :(得分:0)
问题是你在这一行引用它时(即“this”关键字)丢失了方法的上下文:
$("div.question div.sh-answer").click(function(){
$(this).find("div.que-answer").show();
});
这种方式window.onmousemove = this.dragHanlder;
将引用this
:
Window
您可以利用arrow function来保留dragHanlder(event: MouseEvent) {
if (this.isDragging) { <== this === Window
:
this
此处更新了plunkr http://plnkr.co/edit/2LN5EAx9RCdpI3b0Bpt5?p=preview