我正在寻找这种行为http://www.brainjunkie.com/web/js-wordsearch/,但请使用以下方框:
div {
display: inline-block;
width: 100px;
height: 100px;
border: 1px solid black;
cursor: pointer;
}
div.selected,
div:hover {
background-color: red;
color: white;
}
<div>A</div>
<div>B</div>
<div>C</div>
我希望能够在一个框中单击,然后拖动并更改其他框的颜色两个。
我之前发过帖子,但接受答案(我没有意识到我接受的时候对我来说效果不好,因为我正在寻找上面链接中的确切行为。
谢谢。
答案 0 :(得分:0)
For Bresenham’s Line Generation
Assumptions :
1) Line is drawn from left to right.
2) x1 < x2 and y1< y2
3) Slope of the line is between 0 and 1.
We draw a line from lower left to upper
right.
var x1, y1, x2, y2;
function handleMouseDown(e){
x1 = +e.target.dataset.x;
y1 = +e.target.dataset.y;
container.addEventListener('mousemove', handleMouseMove);
e.preventDefault();
}
function handleMouseMove(e){
x2 = +e.target.dataset.x;
y2 = +e.target.dataset.y;
var ele = document.querySelectorAll('[data-x][data-y]');
ele.forEach(function(val){
val.classList.remove('selected')
});
bresenham(x1, y1, x2, y2);
}
function handleMouseUp(e){
var ele = document.querySelectorAll('[data-x][data-y]');
ele.forEach(function(val){
val.classList.remove('selected')
});
e.preventDefault();
container.removeEventListener('mousemove', handleMouseMove);
}
function bresenham(x1 , y1, x2 , y2){
var m_new = 2 * (y2 - y1);
var slope_error_new = m_new - (x2 - x1);
for (var x = x1, y = y1; x <= x2; x++)
{
var ele = document.querySelector('[data-x="'+x+'"][data-y="'+y+'"]');
ele.classList.add('selected');
// Add slope to increment angle formed
slope_error_new += m_new;
// Slope error reached limit, time to
// increment y and update slope error.
if (slope_error_new >= 0)
{
y++;
slope_error_new -= 2 * (x2 - x1);
}
}
}
var container = document.getElementById('container');
container.addEventListener('mousedown', handleMouseDown);
container.addEventListener('mouseup', handleMouseUp);
div {
display: inline-block;
width: 100px;
height: 100px;
border: 1px solid black;
cursor: pointer;
}
div.selected{
background-color: red;
color: white;
}
<span id="container">
<div data-x="0" data-y="0" >A</div>
<div data-x="1" data-y="0" >B</div>
<div data-x="2" data-y="0" >C</div>
</span>