首页 > js拖拽this指向问题?

js拖拽this指向问题?

//问题在js里面的注释位置
$(function() {

var dragging = false;
var iX, iY;
$("#cm-option").mousedown(function(e) {
    dragging = true;
    iX = e.clientX - this.offsetLeft;
    iY = e.clientY - this.offsetTop;
    this.setCapture && this.setCapture();

    return false;
});
document.onmousemove = function(e) {

    if (dragging) {
        var e = e || window.event;
        var oX = e.clientX - iX;
        var oY = e.clientY - iY;
    }
    //当前点击元素的父亲加class on
    //$(this).parent().addClass("on");(这个写法不对,怎么修改)

};
$(document).mouseup(function(e) {
    dragging = false;
    $("#cm-option")[0].releaseCapture();
    e.cancelBubble = true;

})

});


建议
console.log($(this));


你的事件处理函数绑定在document上,$(this)的结果是$(document);要获取当前点击的元素应该用$(e.target)
关于事件对象还有个event.currentTarget,等价于this


this指向document,建议在mousedown的时候把this存在一个变量中,mousemove时使用

$(function(){
    var dragging = false;
var iX, iY;
var that = null;
$("#cm-option").mousedown(function(e) {
    that = $(this);
    dragging = true;
    iX = e.clientX - this.offsetLeft;
    iY = e.clientY - this.offsetTop;
    this.setCapture && this.setCapture();

    return false;
});
document.onmousemove = function(e) {

    if (dragging) {
        var e = e || window.event;
        var oX = e.clientX - iX;
        var oY = e.clientY - iY;
    }
    //当前点击元素的父亲加class on
    that.parent().addClass("on");

};
$(document).mouseup(function(e) {
    dragging = false;
    $("#cm-option")[0].releaseCapture();
    e.cancelBubble = true;

})
});
【热门文章】
【热门文章】