我正在编写一个脚本,要求我创建评级句柄,通过在滑块上拖动它们来提供某些语句的评级。我能够向对象添加一个eventlistener,但不能删除它。
以下是我用来添加和删除事件的代码。
调用addDrag方法的函数,因为它需要参数。
var setDrag = function () {
addDrag(box, bar);
}
将mousedown和mouseup事件添加到“box”元素的功能
bindEvents(box, "mousedown", setDrag);
bindEvents(box, "mouseup", setDrag);
bindEvents(document, "mouseup", setDrag);
addDrag方法:
var addDrag = function (elBox, elBar) {
var mouseStartPosition = event.clientX;
var boxInitMouseAndLeftGap = mouseStartPosition - elBox.getBoundingClientRect().left;
var barInitMouseAndLeftGap = mouseStartPosition - elBar.getBoundingClientRect().left;
var dragHandle = function () {
elBox.style.left = (event.clientX - mouseStartPosition - boxInitMouseAndLeftGap) + "px";
elBar.style.left = (event.clientX - mouseStartPosition - barInitMouseAndLeftGap) + "px";
};
if (event.type == "mousedown") {
bindEvents(document, "mousemove", dragHandle);
}
//HERE WE NEED TO REMOVE THE DRAG FUNCTIONALITY WHEN MOUSEUP IS TRIGGERED ON BOX OR DOCUMENT, THIS IS WHAT IS NOT WORKING FOR ME.
else if (event.type == "mouseup"){
unbindEvents(document, "mousemove", dragHandle);
}
}
以下是为跨浏览器解决方法添加和删除事件的自定义函数:
function bindEvents(el, action, func) {
if (el.addEventListener) { // For all major browsers, except IE 8 and earlier
el.addEventListener(action, func);
} else if (el.attachEvent) { // For IE 8 and earlier versions
el.attachEvent("on" + action, func);
}
return el;
}
function unbindEvents(el, action, func) {
if (el.removeEventListener) { // For all major browsers, except IE 8 and earlier
el.removeEventListener(action, func);
} else if (el.detachEvent) { // For IE 8 and earlier versions
el.detachEvent("on" + action, func);
}
return el;
}