搜尋

首頁  >  問答  >  主體

javascript - 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;

})

});

巴扎黑巴扎黑2895 天前245

全部回覆(3)我來回復

  • 巴扎黑

    巴扎黑2017-04-10 17:16:35

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

    回覆
    0
  • 阿神

    阿神2017-04-10 17:16:35

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

    回覆
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-10 17:16:35

    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;
    
    })
    });

    回覆
    0
  • 取消回覆