如何将 jQuery 代码转换为 JavaScript?

查询:


var isResizing = false,

    lastDownX = 0;


$(function () {

    var container = $('#container'),

        top = $('#top-panel'),

        handle = $('#drag');


    handle.on('mousedown', function (e) {

        isResizing = true;

        lastDownX = e.clientY;

    });


    $(document).on('mousemove', function (e) {

        // we don't want to do anything if we aren't resizing.

        if (!isResizing) 

            return;

        var offsetRight = top.height() + (e.clientY - container.offset().top);


        top.css('top', offsetRight);

    }).on('mouseup', function (e) {

        // stop resizing

        isResizing = false;

    });

});

脚本:


var isResizing = false

// eslint-disable-next-line no-unused-vars

var lastDownX = 0


function resizeVerticallyInit () {

  var top = document.querySelector('#topology-container')

  var handle = document.querySelector('#drag')


  handle.addEventListener('mousedown', function (e) {

    isResizing = true

    lastDownX = e.clientY

  })


  document.addEventListener('mousemove', function (e) {

    // we don't want to do anything if we aren't resizing.

    if (!isResizing) {

      return

    }

    var offsetRight = top.height() + 20


    document.querySelector('#topology-container').style.top = offsetRight

  })


  document.addEventListener('mouseup', function (e) {

    // stop resizing

    isResizing = false

  })

}


mounted () {

  ...

  resizeVerticallyInit()

}

如您所见,我在 mounted() 生命周期方法中的 Vue.js 组件中使用了 JavaScript 函数。


我试图转换它,但它不起作用。


首先我需要说:


// eslint-disable-next-line no-unused-vars

var lastDownX = 0

我不知道为什么它会抱怨 lastDownX 未被使用。


第二个是错误:


"[Vue warn]: Error in mounted hook: "TypeError: Cannot read property 'addEventListener' of null"

它抱怨:


  handle.addEventListener('mousedown', function (e) {

    isResizing = true

    lastDownX = e.clientY

  })

有人可以帮忙转换吗?


潇湘沐
浏览 193回答 1
1回答

紫衣仙女

如果元素不存在于 DOM 中,则First ofdocument.querySelector方法将返回。null您不能调用addEventListenernull。它之所以起作用,jQuery是因为 jquery 构造了一个单独的对象(称为 jQuery 对象)。一个 jQuery 对象看起来有点像这样:{&nbsp; 0: {...} // HTMLElement reference&nbsp; length: 1} // jQuery object该对象公开了一个 jQuery API,它具有on事件处理方法(无论是否存在实际 DOM 元素都可用)。这是 jQuery 的优点(也是缺点)。另一方面,查询选择器方法返回HTMLElement. 如果该元素不存在于 DOM 中,则null返回。现在假设该元素将在一定时间后出现在 DOM 中,您可以做两件事:等待元素出现在 DOM 中,一旦它可用,就添加一个监听器函数。在 JavaScript 中使用live事件(事件委托)。我将向您展示第二种方法:setTimeout(() => {&nbsp; document.querySelector('#container').innerHTML = `<button id="btn">Click</button>`;}, 3000);document.addEventListener('click', (e) => {&nbsp; if (e.target.id === 'btn') {&nbsp; &nbsp; alert('Click works!');&nbsp; }});<div id="container">&nbsp; A button will appear after 3 seconds. However, click event would still work.</div>如您所见,我正在使用e.target它来检测我在文档中单击了哪个元素(我附加了侦听器的位置)。一旦条件匹配,它就会触发alert.&nbsp;这允许我们为最初不存在于 DOM 中的元素绑定事件。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript