gpt4 book ai didi

javascript - 为什么我的事件监听器仅适用于最后一个元素?

转载 作者:行者123 更新时间:2023-11-28 08:38:01 24 4
gpt4 key购买 nike

问题是,当我拖放图片时,它总是放在最后一个字母上。这是我正在谈论的内容的图像:

enter image description here

这是我的代码:

function mattes_draw_letter(x, y, width, height, letter, position)
{
var canvas = document.createElement('canvas');
canvas.style.position = "absolute";
canvas.style.top = 0 + "px";
canvas.id = "canvas_opening_" + position;
canvas.style.zIndex = 5;

var ctx = canvas.getContext("2d");
ctx.lineWidth = 1;
ctx.fillStyle = '#bfbfbf';
ctx.strokeStyle = '#000000';
ctx.beginPath();
ctx.moveTo(x + letter[0] * width, y + letter[1] * height);
for (i = 0; i < letter.length; i+=2)
{
if (typeof letter[i+3] !== 'undefined')
{
ctx.lineTo(x + letter[i+2] * width, y + letter[i+3] * height);
}
}

ctx.fill();
ctx.stroke();
ctx.closePath();

$("#mattes").append(canvas);
canvas.addEventListener("drop", function(event) {drop(event, this);}, false);
canvas.addEventListener("dragover", function(event) {allowDrop(event);}, false);
canvas.addEventListener("click", function() {photos_add_selected_fid(this);}, false);
}

这是具有 for 循环的代码:

function mattes_create_openings(openings)
{
var opening_array = new Array();
var x = 0;
var y = 0;
var opening_width = 0;
var opening_height = 0;

$(openings).each(function(i, el) {

x = $(el).find("x").text() * ppi;
y = $(el).find("y").text() * ppi;
opening_width = $(el).find("width").text() * ppi;
opening_height = $(el).find("height").text() * ppi;
var type = $(el).find("type").text();
var text = $(el).find("text").text();
var ellipse = (type == "ellipse") ? " border-radius: 50% " : "";
if ("letter" == type)
{
var letter = mattes_get_letter_array(text);

var letter_width = (opening_width - (text.length * 0.5 * ppi)) / text.length;
var space = 0.5 * ppi;
var letterX = x;
var letterY = y;
var letter_height = opening_height;

mattes_draw_letter(letterX, letterY, letter_width, letter_height, letter, i);
letterX += (space + letter_width);

}
else
{
$("#mattes").append("<div id='opening_" + i + "' style='background-color: #bfbfbf; position: absolute; left: " + x + "px; top: " + y + "px; height: " + opening_height + "px; width: " + opening_width + "px; overflow: hidden; z-index: 4;" + ellipse + "' ondrop='drop(event, this)' ondragover='allowDrop(event)' onclick='photos_add_selected_fid(this);'>&nbsp;</div>");
}

//TODO multiple openings max/min -x,y,width, height
opening_array["x"] = x;
opening_array["y"] = y;
opening_array["opening_width"] = opening_width;
opening_array["opening_height"] = opening_height;
});
return opening_array;
}

最佳答案

您需要将代码包装在函数调用中的 $.each 中,如下所示:

 $(openings).each(function(i, el) {
bindEvents(i, el);
};
function bindEvents(indx, ele) {
// Code what you have written inside $.each originally
};

关于javascript - 为什么我的事件监听器仅适用于最后一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20840270/

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