鼠标框选元素
js
//selArea 指定框选范围 id initSelection = function(config) { selectionConfig = config; //创建画框选元素 const selector = document.createElement("div"); selector.style.cssText = "position:absolute; pointer-events: none; width:0px; height:0px; font-size:0px; margin:0px;background-color:#70cafc; padding:0px; border:1px solid #0099FF; z-index:1000; filter:alpha(opacity:60); opacity:0.3; display:none"; selector.id = "selector"; document.body.appendChild(selector); //指定框选区域 id const container = document.getElementById(selectionConfig.selArea); //坐标 startX= false; startY = false; isSelecting = false; container.addEventListener('mousedown', selectioNonMouseDown); container.addEventListener('mousemove', selectioNonMouseMove); container.addEventListener('mouseup', selectioNonMouseUp); } selectioNonMouseDown = function(e) { startX = e.clientX; startY = e.clientY; selector.style.left = `${startX}px`; selector.style.top = `${startY}px`; selector.style.width = '0px'; selector.style.height = '0px'; selector.style.display = 'block'; isSelecting = true; } selectioNonMouseMove = function(e) { if (!isSelecting) return; const currentX = e.clientX; const currentY = e.clientY; const width = Math.abs(currentX - startX); const height = Math.abs(currentY - startY); selector.style.width = `${width}px`; selector.style.height = `${height}px`; selector.style.left = `${Math.min(currentX, startX)}px`; selector.style.top = `${Math.min(currentY, startY)}px`; } selectioNonMouseUp = function(e) { isSelecting = false; selectioNcheckSelectedBoxes(); selector.style.display = 'none'; //direction 水平框选方向 let direction = 'r'; if(startX - e.clientX>0){ direction = 'l'; } selectionConfig.success(direction); } selectioNcheckSelectedBoxes = function() { const boxes = document.querySelectorAll(selectionConfig.selItem); //小于5个像素不算拖动 if(selector.clientWidth < 5){ return false; } boxes.forEach(box => { const boxRect = box.getBoundingClientRect(); const selectorRect = selector.getBoundingClientRect(); const isIntersecting = !( boxRect.right < selectorRect.left || boxRect.left > selectorRect.right || boxRect.bottom < selectorRect.top || boxRect.top > selectorRect.bottom ); if (isIntersecting) { box.classList.add(selectionConfig.sleItemClass); } else { box.classList.remove(selectionConfig.sleItemClass); } }); }
调用
//框选 initSelection({ selArea:'selArea', //指定框选区域 id selItem:'.flex-list .item', //指定可框选元素 sleItemClass:'selected',//框先中的元素添加class //成功回调 success:(direction)=>{ //direction 水平框选方向 console.log('框选文件完成'); } });