简体   繁体   中英

Disable jQuery draggable in child element

I am using jQuery draggable . I have added draggable function to main div. Now in all the child elements it's also draggable. How can I disable dragging inside child div if parent is draggable?

 $(function() { $("#draggable").draggable(); });
 #draggable { width: 150px; height: 150px; padding: 0.5em; border: black solid 2px; } .noDrag { width: 100px; height: 50px; border: blue solid 2px; }
 <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <div id="draggable" class="ui-widget-content"> <p>Drag me around</p> <div class='noDrag'>No Drag</div> </div>

To fix this use the cancel property , and provide it a selector to match the element you want to disable the drag behaviour on, like this:

 $(function() { $("#draggable").draggable({ cancel: '.noDrag' }); });
 #draggable { width: 150px; height: 150px; padding: 0.5em; border: black solid 2px; } .noDrag { width: 100px; height: 50px; border: blue solid 2px; }
 <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <div id="draggable" class="ui-widget-content"> <p>Drag me around</p> <div class="noDrag">No Drag</div> </div>

you can use cancel or disableselection() like suggest in jQuery-ui documentation https://jqueryui.com/draggable/#handle

 <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>jQuery UI Draggable - Handles</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <link rel="stylesheet" href="/resources/demos/style.css"> <style> #draggable, #draggable2 { width: 100px; height: 100px; padding: 0.5em; float: left; margin: 0 10px 10px 0; } #draggable p { cursor: move; } </style> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $( function() { $( "#draggable" ).draggable({ handle: "p" }); $( "#draggable2" ).draggable({ cancel: "p.ui-widget-header" }); $( "div, p" ).disableSelection(); } ); </script> </head> <body> <div id="draggable" class="ui-widget-content"> <p class="ui-widget-header">I can be dragged only by this handle</p> </div> <div id="draggable2" class="ui-widget-content"> <p>You can drag me around&hellip;</p> <p class="ui-widget-header">&hellip;but you can't drag me by this handle.</p> </div> </body> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM