var count = 0; elem.onmousemove = function(){ count++; // 当计数器为偶数的时候不执行mousemove if( count % 2 === 0 ){ return; } // 实现拖拽功能的代码... };
var throldHold = 200; //两次scroll事件触发之间最小的事件间隔 window.onscroll = function () { if (arguments.callee.timer) { clearTimeout(arguments.callee.timer); } arguments.callee.timer = setTimeout(isDivScroll, throldHold); } //isDivScroll滚动执行的方法
//函数节流(throttle)与函数去抖(debounce) var throttle = function( fn, timeout ){ var timer; return function(){ var self = this, args = arguments; clearTimeout( timer ); timer = setTimeout(function(){ fn.apply( self, args ); }, timeout ); }; };
window.onmousewheel = throttle(function(){ // 滚轮滚动时的操作代码.. }, 200 );
window.onresize = throttle(function(){ //普通绑定 // 自适应布局的代码... }, 200 ); window.addEventListener("resize", throttle(function(){ //监听绑定 console.log('重置'); },200),false);
var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; } // 添加resize的回调函数,但是只允许它每300毫秒执行一次 window.addEventListener('resize', debounce(function(event) { // 这里写resize过程 },300));
------------------------------------------------------------------------------------
//阻止mouseover和mouseout的反复触发
function contains(parentNode, childNode) { if (parentNode.contains) { return parentNode != childNode && parentNode.contains(childNode); } else { return !!(parentNode.compareDocumentPosition(childNode) & 16); } } function checkHover(e,target){ if (getEvent(e).type=="mouseover") { return !contains(target,getEvent(e).relatedTarget||getEvent(e).fromElement) && !((getEvent(e).relatedTarget||getEvent(e).fromElement)===target); } else { return !contains(target,getEvent(e).relatedTarget||getEvent(e).toElement) && !((getEvent(e).relatedTarget||getEvent(e).toElement)===target); } } function getEvent(e){ return e||window.event; } document.getElementById("element").addEventListener("mouseover",function(e){ if(checkHover(e,this)){ console.log('鼠标进去一次'); } },false);