2012-04-25 32 views
17

Tôi đang cố gắng ngăn sự kiện con lăn được chụp bởi một phần tử của trang để gây ra cuộn.Javascript: Chụp sự kiện bánh xe chuột và không cuộn trang?

tôi mong đợi 'false' như tham số cuối cùng để có kết quả mong đợi, nhưng sử dụng bánh xe chuột qua yếu tố này "vải" vẫn gây di chuyển:

this.canvas.addEventListener('mousewheel',function(event){mouseController.wheel(event)}, false); 

Ngoài yếu tố này "vải", cuộn cần phải xảy ra. Bên trong, nó chỉ phải kích hoạt phương thức .wheel(). Tôi đang làm gì sai?

Cảm ơn! J.

Trả lời

29

Bạn có thể làm như vậy bằng cách trả lại false ở cuối trình xử lý.

this.canvas.addEventListener('mousewheel',function(event){ 
    mouseController.wheel(event); 
    return false; 
}, false); 
+1

+1: Tôi đã có cùng một vấn đề chính xác như thế này và một 'return false;' làm việc –

+0

Được rồi! Thật vậy, điều đó làm điều đó. Cảm ơn :-) – Jem

+0

Tôi thấy lạ rằng sai nghĩa là sự kiện được xử lý. Đúng hơn sẽ hợp lý hơn ... –

19

Bạn đã thử event.preventDefault() chưa?

this.canvas.addEventListener('mousewheel',function(event){ 
    mouseController.wheel(event); 
    event.preventDefault(); 
}, false); 
+0

Yep, giống như chức năng (sự kiện) {event.preventDefault(); mouseController.wheel (event)} – Jem

+0

Ahh, tôi quên trả về false. Cảm ơn vì đã dành thời gian cho tôi! – Jem

1

Loại hủy này dường như bị bỏ qua trong Chrome mới hơn> 18 Trình duyệt (và có lẽ các trình duyệt dựa trên WebKit khác). Để nắm bắt độc quyền sự kiện, bạn phải trực tiếp thay đổi phương thức onmousewheel của phần tử.

this.canvas.onmousewheel = function(ev){ 
    //perform your own Event dispatching here 
    return false; 
}; 
2

Chỉ cần thêm, tôi biết rằng canvas chỉ HTML5 vì vậy đây là không cần thiết, nhưng chỉ trong trường hợp ai đó muốn crossbrowser tương thích/oldbrowser, sử dụng này:

/* To attach the event: */ 
addEvent(el, ev, func) { 
    if (el.addEventListener) { 
     el.addEventListener(ev, func, false); 
    } else if (el.attachEvent) { 
     el.attachEvent("on" + ev, func); 
    } else { 
     el["on"+ev] = func; // Note that this line does not stack events. You must write you own stacker if you don't want overwrite the last event added of the same type. Btw, if you are going to have only one function for each event this is perfectly fine. 
    } 
} 

/* To prevent the event: */ 
addEvent(this.canvas, "mousewheel", function(event) { 
    if (!event) event = window.event; 
    event.returnValue = false; 
    if (event.preventDefault)event.preventDefault(); 
    return false; 
}); 
Các vấn đề liên quan