如何在jQuery Mobile中使用TouchPunch.js实现页面元素拖拽?
Hey there! Let's get those dynamically created elements draggable with TouchPunch sorted out. Since you've already got the core scripts set up correctly, here's what you need to focus on for dynamic elements:
First, let's confirm your current script setup (great job getting these in the right order!):
<script src="http://code.jquery.com/jquery.min.js"></script> <script src="http://code.jquery.com/ui/1.8.21/jquery-ui.min.js"></script> <script src="jquery.ui.touch-punch.min.js"></script>
The critical thing to note: jQuery UI's draggable() (and TouchPunch's touch extension for it) doesn't automatically apply to elements created after the initial page load. Here are two reliable fixes:
1. Initialize Draggable Immediately After Creating the Element
As soon as you generate your dynamic element in code, call draggable() on it right away. Here's a quick example:
// Create a dynamic draggable element const dynamicItem = $('<div class="draggable-box">I\'m a dynamic drag item!</div>'); $('.container').append(dynamicItem); // Apply draggable (TouchPunch will handle touch events automatically) dynamicItem.draggable({ containment: '.container', // Optional: keep element within a parent bounds cursor: 'grab' });
2. Use a Mutation Observer for Scalable Setups
If you're adding elements frequently or want a more hands-off approach, a mutation observer can detect when new elements are added to the DOM and initialize draggable for them:
// Target the parent where dynamic elements will be added const parentContainer = $('.container')[0]; // Set up the observer to watch for new child elements const observer = new MutationObserver((mutations) => { mutations.forEach(mutation => { mutation.addedNodes.forEach(node => { // Check if the new node is your draggable element (adjust selector as needed) if ($(node).hasClass('draggable-box')) { $(node).draggable({ containment: '.container', cursor: 'grab' }); } }); }); }); // Start observing the parent container observer.observe(parentContainer, { childList: true, subtree: true });
Quick Troubleshooting Checks
- Double-check in WebStorm's DevTools (Network tab) that all three scripts load without 404 errors—order matters, and TouchPunch must come after jQuery and jQuery UI.
- Ensure your dynamic elements have a defined width/height (draggable can fail if elements are visually collapsed).
- Test with Chrome's DevTools Device Toolbar to simulate touch events, confirming TouchPunch is intercepting touch inputs properly.
内容的提问来源于stack exchange,提问作者RW6

