鼠标事件应用实例--鼠标轨迹和列表拖拽

247 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第9天,点击查看活动详情

鼠标轨迹特效

通过鼠标移入和移出事件,实现一个鼠标轨迹特效

实现步骤

  1. 生成小方块矩阵
<div class="container" id="container"></div>
let span = '<span></span>'.repeat(1000)
document.querySelector('#container').insertAdjacentHTML('beforeend', span)
  1. 这个函数实现设置小方块颜色,并且绑定到鼠标移入事件
const colors = ['#f387b6', '#ef59a0', '#fff24a', '#0ab99b', '#d5193d', '#00bbf2', '#a2ce59', '#f46b43', '#d9e2f1', '#fcff00']
function setColor(element) {
    //your complement
    element.style.background = colors[Math.floor(Math.random() * 9)]
    element.style.transition = 'background 0s'
}
document.querySelector('#container').onmouseout = function(e) {
    if(e.target.tagName == 'SPAN'){
            deleteColor(e.target)
    }
}
  1. 这个函数实现去除小方块颜色,并添加一个过度效果。绑定到鼠标移出事件
function deleteColor(element) {
    //your complement
    element.style.background = '#333'
    element.style.transition = 'background 2s'
}
document.querySelector('#container').onmouseout = function(e) {
    if(e.target.tagName == 'SPAN'){
            deleteColor(e.target)
    }
}

实现任务列表拖拽效果

待补充。。。。