Web实现悬浮球 | 您所在的位置:网站首页 › 谷歌点按翻译悬浮球怎么开启 › Web实现悬浮球 |
这次要实现的是这种效果,能够在页面上推拽和点击的,拖拽的话,就跟随鼠标移动,点击的话,就触发新的行为,当然也有指定某些区域不能拖拽,接下来就一起来看看有什么难点吧~ 需要监听的鼠标事件 既然是web页面,那肯定要监听的就算鼠标事件 mousedown(MDN: developer.mozilla.org/zh-CN/docs/…) mousemove(MDN: developer.mozilla.org/zh-CN/docs/… ) mouseup(MDN: developer.mozilla.org/zh-CN/docs/…) 这三个事件应该大家都不陌生mousedown(鼠标按下),mousemove(鼠标移动), mouseup(鼠标抬起) mousedown window.onload = () => { ballDom.addEventListener('mousedown', ballMoveDown) ballDom.addEventListener('touchstart', ballMoveDown) } window.unload = () => { ballDom.removeEventListener('mousedown', ballMoveDown) ballDom.removeEventListener('touchstart', ballMoveDown) }页面初始化完成就监听这两个事件,touchstart是为了在移动端也能正常,所以也监听。 页面卸载,就取消绑定事件。 接下来就算鼠标按下事件触发,就需要监听鼠标移动和鼠标抬起事件 const ballMoveDown = (event) => { window.addEventListener('mousemove', ballMove, false) window.addEventListener('mouseup', ballUp, false) window.addEventListener('touchmove', ballMove, false) window.addEventListener('touchend', ballUp, false) } mouseup同样,鼠标抬起,需要把这些事件给取消 const ballUp = (event) => { // 移除鼠标移动事件 window.removeEventListener('mousemove', ballMove) window.removeEventListener('touchmove', ballMove) // 移除鼠标松开事件 window.removeEventListener('mouseup', ballUp) window.removeEventListener('touchend', ballUp) }接下来,最重要的就是鼠标移动 mousemove由于鼠标移动到哪里,我们需要把悬浮球也移动到相应的位置,所以我这里使用的是transform属性,使用这个属性的好处就是,不会脱离 |
CopyRight 2018-2019 实验室设备网 版权所有 |