Drag and drop anywhere on screen with multiple elements of the same ID Class and Tag HTML

前端 未结 2 491
北恋
北恋 2021-01-16 02:13

Hello everyone this is my first question so I might have done it wrong. What I am trying to achieve is is have multiple

2条回答
  •  野的像风
    2021-01-16 02:40

    Don't know if you want to use Jquery or not, but I know it's way simpler than the raw javascript solution. I've been searching the internet and Stack Overflow for a simple drag-and-drop anywhere on a web page solution, but I couldn't find one that worked. The other answers to this question have been weird for me. They sometimes work, sometimes don't. However, a friend suggested using the Jquery version, and wow, it's so much simpler. Just one line of code!

    var dragme = document.getElementsByClassName("dragme");
    		for (var i = 0; i < dragme.length; i++) {
    			$(dragme[i]).draggable();
    		}
    .dragme {
      cursor: move;
    }
    
    
    

    Try dragging me anywhere on this sample!

    Drag me, too!

    IMPORTANT NOTE: This code does not work with just Jquery, it also requires the Jquery UI file.

    If the above sample does not work for you, please comment the error it show below. Note that this works for an unlimited amount of elements. This specific example is for elements with the class "dragme", so just replace that with your own class. For one element, it is a single line of code: $("#yourid").draggable();.

    This code works for me on Google Chrome. Hope this helps anyone coming on to this page late, like me!

提交回复
热议问题