求助:将指定jQuery鼠标事件函数转换为原生JavaScript函数
Converting jQuery's Namespaced Event Binding to Vanilla JavaScript
Got it, let's fix up your vanilla JS conversion step by step. The main confusion here is handling jQuery's namespaced event bindings (like mousemove.rotateImg) since vanilla JS doesn't have built-in event namespaces. But we can replicate the core functionality with a reusable event handler function.
Complete Vanilla JS Code
// Define the rotate handler as a reusable variable (for precise unbinding later) const rotateImgHandler = function(e) { rotateOnMouse(e, document.querySelector('.top')); }; // Bind mousedown event to .top1 element document.querySelector(".top1").addEventListener("mousedown", function(e) { e.preventDefault(); // Stop default image dragging behavior if (e.shiftKey) { console.log('Shift + mousedown detected'); // Attach the mousemove listener to document document.addEventListener('mousemove', rotateImgHandler); // Add cleanup logic to stop listening when mouse is released function cleanupRotation() { document.removeEventListener('mousemove', rotateImgHandler); document.removeEventListener('mouseup', cleanupRotation); // Remove this cleanup handler too } document.addEventListener('mouseup', cleanupRotation); } });
Key Details & Explanations
Replacing
$(document).bind('mousemove.rotateImg', ...)- jQuery's namespaced events let you unbind only a specific handler without disrupting other
mousemovelisteners. In vanilla JS, we replicate this by storing our handler in a variable (rotateImgHandler). This lets us pass the exact same function toremoveEventListener()when we need to stop listening.
- jQuery's namespaced events let you unbind only a specific handler without disrupting other
Critical Cleanup Step
- Your original jQuery code likely had a corresponding
$(document).unbind('mousemove.rotateImg')(probably triggered onmouseup). In vanilla JS, we add amouseuplistener that removes both themousemovehandler and itself to avoid leftover, unwanted event bindings.
- Your original jQuery code likely had a corresponding
jQuery Selector Conversion
$('.top')translates todocument.querySelector('.top')for a single matching element. If you need to target multiple.topelements, usedocument.querySelectorAll('.top')and adjust therotateOnMousefunction to handle a NodeList.
内容的提问来源于stack exchange,提问作者Maanas Hegde
相关产品推荐
相关产品推荐

