Following the examples in the jQuery UI demo and documentation , I'm using this HTML:
<ul class="sort">
<li>
<button>A</button>
</li>
<li>
<button>B</button>
</li>
<li>
<button>C</button>
</li>
</ul>
And this JS:
$(function () {
$('.sort').sortable();
})
But as seen in this JSFiddle example , the buttons are not drag-able.
How can I make .sortable() work with buttons?
Sortable provides a cancel
selector to prevent sorting on specified elements. The default value includes <button>
elements, and your sort handles are buttons, so sorting is prevented:
cancel
Type: Selector
Default: "input,textarea,button,select,option"
Prevents sorting if you start on elements matching the selector.
To solve this, set the cancel
selector to an empty string:
$('.sort').sortable({ cancel: '' });
ul { list-style: none; margin: 0; padding: 0; width: 100px; } button { width: 100%; }
<link href="//code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="//code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <ul class="sort"> <li><button>A</button></li> <li><button>B</button></li> <li><button>C</button></li> </ul>
Also, you can specify the draggable handles for sortable()
by using the handle
option :
$('.sort').sortable({handle:'button'});
But in your case, the entire content of each <li>
element is a <button>
, so you won't need to specify it.
Ahhh, you know what? jQuery UI prevents .sortable() from working on buttons by default, as stated in the .cancel() section of the documentation ! Clearing this default allows the buttons to be sort-able like in this updated example .
The functional JS/jQuery looks like this:
$(function () {
$('.sort').sortable({
cancel: ''
});
})
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.