var canvas = document.getElementById('mainCanvas');
var ctx = canvas.getContext('2d');
var status = document.getElementById('status');
var click = document.getElementById('click');
var hover = document.getElementById('hover');
canvas.style.backgroundColor = 'red';
var mouseX;
var mouseY;
var item1 = new item('item1', ctx);
item1.drawItem(50, 50);
var item2 = new item('item2', ctx);
item2.drawItem(150, 200);
var item3 = new item('item3', ctx);
item3.drawItem(200, 250);
var items = [item1, item2, item3];
canvas.addEventListener('mousemove', mouseMoveHandler, false);
canvas.addEventListener('click', mouseClickHandler, false);
function mouseMoveHandler(event) {
mouseX = event.clientX - canvas.getBoundingClientRect().left;
mouseY = event.clientY - canvas.getBoundingClientRect().top;
for (var i = 0; i < items.length; i++) {
if (mouseX > items[i].x & mouseY > items[i].y &
mouseX < items[i].x + items[i].width & mouseY < items[i].y + items[i].height) {
hover.innerHTML = items[i].name;
} else {
hover.innerHTML = 'No';
}
}
}
function mouseClickHandler(event) {
click.innerHTML = mouseX + ' | ' + mouseY;
}
function item(name, ctx) {
this.x = undefined;
this.y = undefined;
this.width = 50;
this.height = 50;
this.name = name;
this.drawItem = function(x, y) {
ctx.fillRect(this.x = x, this.y = y, this.width, this.height);
}
}
&#13;
<div class='canvas'>
<canvas id='mainCanvas' width='500' height='300'></canvas>
</div>
<p id='click'>0 | 0</p>
<p id='hover'>No</p>
&#13;
我想要完成的任务:
当鼠标悬停在画布中的每个方块(或项目)时,我想要正方形的名称(在创建每个项目时指定为第一个参数)以显示为悬停元素。
我得到了什么:
它有点奏效,但只适用于最后一个方格。每当我将鼠标悬停在不是最后一个方格的任何其他方格上时,“悬停”#39; element不显示鼠标所在方块的名称。我甚至创建并添加了一个新项目到&#39;项目&#39;数组并且它与新的一起工作,但不与其他工作。
答案 0 :(得分:2)
你的问题是找到命中后for循环继续运行。让我们说你的鼠标item2。您的代码将工作并显示“item2”。然后循环进入下一步并检查您是否将鼠标悬停在item3上。你不这样做,所以代码显示'no'。
解决方案是在点击后停止循环
$ python3 read.py
Searching for job 'name 1'
'name 1' : Found in 'job 2, name 1...\n'
Searching for job 'name 2'
'name 2' : Found in 'job 1, name 2...\n'
Searching for job 'name 3'