You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:将指定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

  1. Replacing $(document).bind('mousemove.rotateImg', ...)

    • jQuery's namespaced events let you unbind only a specific handler without disrupting other mousemove listeners. In vanilla JS, we replicate this by storing our handler in a variable (rotateImgHandler). This lets us pass the exact same function to removeEventListener() when we need to stop listening.
  2. Critical Cleanup Step

    • Your original jQuery code likely had a corresponding $(document).unbind('mousemove.rotateImg') (probably triggered on mouseup). In vanilla JS, we add a mouseup listener that removes both the mousemove handler and itself to avoid leftover, unwanted event bindings.
  3. jQuery Selector Conversion

    • $('.top') translates to document.querySelector('.top') for a single matching element. If you need to target multiple .top elements, use document.querySelectorAll('.top') and adjust the rotateOnMouse function to handle a NodeList.

内容的提问来源于stack exchange,提问作者Maanas Hegde

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:05:13