console
window.onload = function(){
let lis = document.querySelectorAll('li');
document.addEventListener('mousedown', e=>{
if(e.button == 2) {return;}
let starPos = {
x: e.clientX,
y: e.clientY,
};
let oDiv = document.createElement('div');
oDiv.className = 'draw-div';
document.body.appendChild(oDiv);
let check = function(el1, el2){
console.log(1);
let el1Rect = el1.getBoundingClientRect();
let el2Rect = el2.getBoundingClientRect();
if(el1Rect.right < el2Rect.left ||
el1Rect.bottom < el2Rect.top ||
el1Rect.left > el2Rect.right ||
el1Rect.top > el2Rect.bottom) {
return false;
}else {
return true;
}
}
let checkEveryOne = (el1, els) => {
els.forEach(item=>{
let choose = check(el1, item);
if(choose) {
item.className = 'active';
} else {
item.className = '';
}
});
}
let move = e=>{
let nowPos = {
x: e.clientX,
y: e.clientY
};
let dis = {
x: Math.abs(nowPos.x - starPos.x),
y: Math.abs(nowPos.y - starPos.y)
};
checkEveryOne(oDiv, lis);
oDiv.style.left = Math.min(nowPos.x, starPos.x) + 'px';
oDiv.style.top = Math.min(nowPos.y, starPos.y) + 'px';
oDiv.style.width = dis.x + 'px';
oDiv.style.height = dis.y + 'px';
};
document.addEventListener('mousemove', move);
document.addEventListener('mouseup', ()=>{
oDiv.remove();
document.removeEventListener('mousemove', move);
}, {once: true});
e.preventDefault();
});
}
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
body,div,ul,li {margin: 0; padding: 0;}
ul {list-style: none;}
li { width: 100px; height: 100px; float: left; border: 1px solid #f00; margin: 10px;}
li.active { background: #0f0;}
.draw-div { position: absolute; border: 1px solid #eee; background: rgba(255, 255, 0, 0.5);}