gpt4 book ai didi

javascript - 事件处理程序没有响应

转载 作者:行者123 更新时间:2023-12-03 00:42:13 24 4
gpt4 key购买 nike

我从 JavaScript 和 D3 开始,尝试编写一个简单的代码,允许用户在 Canvas 上绘制曲线。第一步是能够检测鼠标按钮何时按下,这样如果鼠标在按钮按下时移动,数据就会被记录。

我尝试将“.on”更改为“.addEventListener”,但结果相同。另外,我正在使用 Firefox。

当阅读下面的代码时,我知道每次移动鼠标时让标志 clickState 递增没有什么意义;我这样做只是为了调试目的,看看函数 mousemovefx 是否在鼠标移动时被调用。

当我打开此网页时,输出 div 中的文本立即更改为“向下”,并且我所做的任何操作(例如在 Canvas 中单击和移动)都不会更改它。其他函数似乎也没有被执行。

我既不明白(a)为什么在这些事件上没有调用处理程序,也不明白(b)为什么当我不仅没有点击而且我的鼠标甚至不在 Canvas 上时立即调用 mousedown 处理程序.

    document.body.style.backgroundColor = "black";

canvw = 500;
canvh = 500;
border = 6;

clickState = 0;

var canvas = d3.select("body")
.append("svg") //Add an SVG to the body
.attr("width",canvw+2*border)
.attr("height",canvh+2*border)

var canvbg = canvas.append("rect")
.attr("x",border)
.attr("y",border)
.attr("width",canvw)
.attr("height",canvh)
.attr("fill","white")
.attr("stroke","rgb(200,200,200)")
.attr("stroke-width",5)

var mydiv = d3.select("body")
.append("div")
.attr("id","outputdiv")
.style("color","orange")

canvas.on("mousedown", mousedownfx());

canvas.on("mouseup", mouseupfx());

canvas.on("mousemove",mousemovefx());

canvas.on("mouseout",mouseoutfx());

function mousedownfx() {
clickState = 1;
mydiv.text("Down")
}

function mouseupfx() {
clickState = 0;
mydiv.text("Up")
}

function mousemovefx() {
mydiv.text(clickState)
clickState = clickState + 1;
}

function mouseoutfx() {
clickstate = 0;
}

最佳答案

document.body.style.backgroundColor = "black";

canvw = 500;
canvh = 500;
border = 6;

clickState = 0;

var canvas = d3.select("body")
.append("svg") //Add an SVG to the body
.attr("width",canvw+2*border)
.attr("height",canvh+2*border)

var canvbg = canvas.append("rect")
.attr("x",border)
.attr("y",border)
.attr("width",canvw)
.attr("height",canvh)
.attr("fill","white")
.attr("stroke","rgb(200,200,200)")
.attr("stroke-width",5)

var mydiv = d3.select("body")
.append("div")
.attr("id","outputdiv")
.style("color","orange")

canvas.on("mousedown", mousedownfx);

canvas.on("mouseup", mouseupfx);

canvas.on("mousemove",mousemovefx);

canvas.on("mouseout",mouseoutfx);

function mousedownfx() {
clickState = 1;
mydiv.text("Down")
}

function mouseupfx() {
clickState = 0;
mydiv.text("Up")
}

function mousemovefx() {
mydiv.text(clickState)
clickState = clickState + 1;
}

function mouseoutfx() {
clickstate = 0;
}
<script src="https://d3js.org/d3.v5.min.js"></script>

当您设置监听器时,您正在调用函数更改:

canvas.on("mousedown", mousedownfx());
canvas.on("mouseup", mouseupfx());
canvas.on("mousemove",mousemovefx());
canvas.on("mouseout",mouseoutfx());

致:

canvas.on("mousedown", mousedownfx);
canvas.on("mouseup", mouseupfx);
canvas.on("mousemove",mousemovefx);
canvas.on("mouseout",mouseoutfx);

这将传递该函数,然后单击按钮时将调用该函数。

关于javascript - 事件处理程序没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53401682/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com