禁用子元素

时间:2017-09-15 09:21:57

标签: javascript jquery jquery-ui

我正在使用jQuery draggable。我已经为主div添加了可拖动功能。现在在所有的儿童元素中,它也是可以拖拽的。如果父项可拖动,如何在子div中禁用拖动?



$(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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:5)

要解决此问题,请使用cancel property,并为其提供一个选择器,以匹配您要禁用拖动行为的元素,如下所示:

&#13;
&#13;
$(function() {
  $("#draggable").draggable({
    cancel: '.noDrag'
  });
});
&#13;
#draggable {
  width: 150px;
  height: 150px;
  padding: 0.5em;
  border: black solid 2px;
}

.noDrag {
  width: 100px;
  height: 50px;
  border: blue solid 2px;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用cancel或disableselection(),如jQuery-ui文档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>