在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/網絡安全  HTML/ 如何合理節(jié)流onmousemove事件?

如何合理節(jié)流onmousemove事件?

    //鼠標點擊開始
    center[0].onmousedown = function () {
    
        docMove();

        //數據釋放
        document.onmouseup = function () {
            document.onmousemove = null;
            document.onmouseup = null;
        };
    };

    function docMove() {
        document.onmousemove = function (e) {
            var e     = e || window.event;
            var newX  = e.clientX;
            
           //通過newX動態(tài)設置元素css來達到改變位置的效果
           
            //阻止冒泡
            e.stopPropagation();
        };
    }

問題:如何通過setTimeout達到函數節(jié)流,提升性能?
PS:目前事件執(zhí)行還有一個小問題,就是在移動元素的過程中會間接性出現鼠標已經釋放但onmousemove 并未失效的問題,(實際觀感就是鼠標左鍵已經釋放,但是元素還會跟著鼠標移動)

回答
編輯回答
小眼睛

你也聽到通過 setTimeout 進行節(jié)流。那么你應該明白節(jié)流的原理?將事件綁定,然后將事件取消,又綁定。即定義某個操作,然后在 setTimeout 內部刪除,然后設置新的開始 setTimeout,在新的開始后又重新綁定結束刪除,遞歸就行。具體根據需求完成罷。

2017年5月3日 06:24
編輯回答
魚梓

函數節(jié)流:

var t = null
document.addEventListener('mousemove', () => {
    if (t === null) {
        t = setTimeout(() => {
            console.log('執(zhí)行')
            t = null
        }, 16)
    }
}, false)

為何是 16ms 間隔請參考:https://www.cnblogs.com/liuha...

鼠標釋放元素依然移動:可以在 onmousedown 時開啟元素可移動的開關,onmouseup 時關閉元素可移動的開關,onmousemove 時判斷開關的狀態(tài)決定是否執(zhí)行元素移動的回調,開關即為一個自己聲明的布爾型的變量。

var flag = false
document.addEventListener('mousedown', () => {
    flag = true
}, false)
document.addEventListener('mousemove', () => {
    if (flag) console.log('執(zhí)行元素移動')
}, false)
document.addEventListener('mouseup', () => {
    flag = false
}, false)
2017年1月5日 18:01
編輯回答
巫婆

實現思路就是判斷觸發(fā)事件的時間和上次觸發(fā)事件的時間間隔超過設定值才觸發(fā)新的處理函數。

建議使用loadsh等類庫現成的節(jié)流構造函數即可,自己實現當然也行。

2017年4月5日 22:35
編輯回答
影魅
dom.onmousemove=function(){
     if (this.time && Date.now() - this.time < 50) return
     this.time = Date.now()
    // you code
}

如果在移動元素的回調里節(jié)流,會導致移動卡卡的.最好不要高于16(1000/60,顯示器一般刷新率是60幀/秒)

附贈一個簡單的拖拽吧

  let box = document.querySelector('.box')
  document.onmousedown = function (e) {
    let down = false
    if (e.target === box) {
      down = true
      e.target.x = e.offsetX
      e.target.y = e.offsetY
    }
    document.onmousemove = function (e) {
      if (!down) return
      if (this.time && (Date.now() - this.time) < 16) return
      this.time = Date.now()
      box.style.transform = `translate3d(${e.clientX - box.x}px,${e.clientY - box.y}px,0)`
    }
    document.onmouseup = clear
  }

  function clear() {
    document.onmouseup = document.onmousemove = null
  }
2017年8月26日 23:03