升级jQuery 3.3.1后e.pageX/e.pageY失效的替代方案咨询
Got it, let's fix that drag functionality issue you're facing after upgrading to jQuery 3.3.1. The good news is there are several straightforward ways to get back that pageX/pageY behavior—here are your best options:
1. Use the Native Event's pageX/pageY Directly
jQuery 3.0 removed the normalization of pageX/pageY, but these properties still exist on the native DOM event object. You can access them via event.originalEvent in your jQuery event handlers.
Example code for your drag handler:
$('.your-drag-element').on('drag', function(event) { // Get native event properties const pageX = event.originalEvent.pageX; const pageY = event.originalEvent.pageY; // Use these values in your position calculation logic console.log(`Current position: ${pageX}, ${pageY}`); });
This is the quickest fix—no extra code needed, just a small adjustment to how you access the coordinates.
2. Implement pageX/pageY Yourself
If for some reason you can't access the native event (unlikely, but possible), you can calculate these values manually using clientX/clientY plus the window's scroll offsets.
Here's a reusable function to do this:
function getPageCoordinates(event) { const eventDoc = event.target.ownerDocument || document; const doc = eventDoc.documentElement; const body = eventDoc.body; const pageX = event.clientX + (doc.scrollLeft || body.scrollLeft) - (doc.clientLeft || body.clientLeft); const pageY = event.clientY + (doc.scrollTop || body.scrollTop) - (doc.clientTop || body.clientTop); return { pageX, pageY }; }
Then use it in your handler:
$('.your-drag-element').on('drag', function(event) { const { pageX, pageY } = getPageCoordinates(event.originalEvent || event); // Your position logic here });
3. Reuse Older jQuery's Normalization Code
If you want to replicate exactly how jQuery handled pageX/pageY before version 3, you can extract the relevant code from older jQuery versions (like 2.2.4) and wrap it into a utility.
Here's the stripped-down code from jQuery's event normalization:
function normalizeEventPageCoords(event) { if (event.pageX === undefined && event.clientX !== undefined) { const doc = document.documentElement; const body = document.body; event.pageX = event.clientX + (doc.scrollLeft || body.scrollLeft) - (doc.clientLeft || 0); event.pageY = event.clientY + (doc.scrollTop || body.scrollTop) - (doc.clientTop || 0); } return event; }
You can call this function at the start of your drag handler to add pageX/pageY back to the jQuery event object:
$('.your-drag-element').on('drag', function(event) { normalizeEventPageCoords(event.originalEvent); // Now you can use event.originalEvent.pageX/pageY as before });
All three methods should resolve your issue with dragging elements outside the multi-select div—just pick the one that fits your codebase best!
内容的提问来源于stack exchange,提问作者Pascut

