Drag and drop without JQuery UI

后端 未结 7 914
春和景丽
春和景丽 2020-12-14 19:50

I searched a lot to find a tutorial for drag & drop with jQuery alone (without UI), but due to the popularity of JQuery UI, all drag and drop features are based on JQuer

7条回答
  •  旧巷少年郎
    2020-12-14 20:15

    Answer based on: https://www.sanwebe.com/2014/10/draggable-element-with-jquery-no-jquery-ui

    for sorting perhaps see: http://johnny.github.io/jquery-sortable/

    var draggable = $('#dragit'); //element 
    
    draggable.on('mousedown', function(e){
    	var dr = $(this).addClass("drag").css("cursor","move");
    	height = dr.outerHeight();
    	width = dr.outerWidth();
    	ypos = dr.offset().top + height - e.pageY,
    	xpos = dr.offset().left + width - e.pageX;
    	$(document.body).on('mousemove', function(e){
    		var itop = e.pageY + ypos - height;
    		var ileft = e.pageX + xpos - width;
    		if(dr.hasClass("drag")){
    			dr.offset({top: itop,left: ileft});
    		}
    	}).on('mouseup', function(e){
    			dr.removeClass("drag");
    	});
    });
    #dragit
      {
        background: red;
        width: 50px;
        height: 50px;
        cursor: move;
        position: relative;
      }
    
    
    Drag me

    Constrain movement

    var draggable = $('#dragit-contained'); //element 
    
    draggable.on('mousedown', function(e){
    	var dr = $(this).addClass("drag").css("cursor","move");
    	height = dr.outerHeight();
    	width = dr.outerWidth();
    	max_left = dr.parent().offset().left + dr.parent().width() - dr.width();
    	max_top = dr.parent().offset().top + dr.parent().height() - dr.height();
    	min_left = dr.parent().offset().left;
    	min_top = dr.parent().offset().top;
    
    	ypos = dr.offset().top + height - e.pageY,
    	xpos = dr.offset().left + width - e.pageX;
    	$(document.body).on('mousemove', function(e){
    		var itop = e.pageY + ypos - height;
    		var ileft = e.pageX + xpos - width;
    		
    		if(dr.hasClass("drag")){
    			if(itop <= min_top ) { itop = min_top; }
    			if(ileft <= min_left ) { ileft = min_left; }
    			if(itop >= max_top ) { itop = max_top; }
    			if(ileft >= max_left ) { ileft = max_left; }
    			dr.offset({ top: itop,left: ileft});
    		}
    	}).on('mouseup', function(e){
    			dr.removeClass("drag");
    	});
    });
    .draggable-area
      {
        background: grey;
        width: 320px;
        height: 240px;
      }
    #dragit-contained
      {
        background: red;
        width: 50px;
        height: 50px;
        cursor: move;
        position: relative;
      }
    
    
    Drag me

提交回复
热议问题