20道JS原理题助你面试一臂之力(必看)(3)

window.onload = function () { // drag处于绝对定位状态 let drag = document.getElementById('box') drag.onmousedown = function(e) { var e = e || window.event // 鼠标与拖拽元素边界的距离 = 鼠标与可视区边界的距离 - 拖拽元素与边界的距离 let diffX = e.clientX - drag.offsetLeft let diffY = e.clientY - drag.offsetTop drag.onmousemove = function (e) { // 拖拽元素移动的距离 = 鼠标与可视区边界的距离 - 鼠标与拖拽元素边界的距离 let left = e.clientX - diffX let top = e.clientY - diffY // 避免拖拽出可视区 if (left < 0) { left = 0 } else if (left > window.innerWidth - drag.offsetWidth) { left = window.innerWidth - drag.offsetWidth } if (top < 0) { top = 0 } else if (top > window.innerHeight - drag.offsetHeight) { top = window.innerHeight - drag.offsetHeight } drag.style.left = left + 'px' drag.style.top = top + 'px' } drag.onmouseup = function (e) { this.onmousemove = null this.onmouseup = null } } }

19. 实现一个节流函数

// 思路:在规定时间内只触发一次 function throttle (fn, delay) { // 利用闭包保存时间 let prev = Date.now() return function () { let context = this let arg = arguments let now = Date.now() if (now - prev >= delay) { fn.apply(context, arg) prev = Date.now() } } } function fn () { console.log('节流') } addEventListener('scroll', throttle(fn, 1000))

20. 实现一个防抖函数

// 思路:在规定时间内未触发第二次,则执行 function debounce (fn, delay) { // 利用闭包保存定时器 let timer = null return function () { let context = this let arg = arguments // 在规定时间内再次触发会先清除定时器后再重设定时器 clearTimeout(timer) timer = setTimeout(function () { fn.apply(context, arg) }, delay) } } function fn () { console.log('防抖') } addEventListener('scroll', debounce(fn, 1000))

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/cef2f83d97886b56378bf930073bb469.html