javascript - Javascript 使用 onclick 附加 div 元素需要双击
问题描述
我正在创建一个 div 元素并添加一个 onclick 以在屏幕上拖动元素。拖动本身按预期工作,但在我双击元素之前它不起作用。知道为什么我需要双击每个元素才能在屏幕上拖动它们/我可以做些什么来通过单击拖动元素?
在我开始从 JS 内部动态构建它们之前,我不需要双击这些元素。
这是添加 onclick 的行:
node.onclick = function(){
dragElement(document.getElementById(this.id));
}
这是整个函数:
function buildCards(){
for(let x=0;x<4;x++){
for(let i=0;i<13;i++){
var individualCard = new Object();
individualCard.value = i;
if(x == 0){
individualCard.type = 'club';
individualCard.color = 'black';
}else if(x == 1){
individualCard.type = 'spade';
individualCard.color = 'black';
}else if(x == 2){
individualCard.type = 'heart';
individualCard.color = 'red';
}else{
individualCard.type = 'diamond';
individualCard.color = 'red';
}
individualCard.id = individualCard.color+'-'+individualCard.value+'-'+individualCard.type;
deckOfCards.push(individualCard);
let node = document.createElement('div');
node.className = 'cards';
node.setAttribute("id", individualCard.id);
node.onclick = function(){
dragElement(document.getElementById(this.id));
}
node.style.background = 'url("cards/cards.png") '+-(i*72)+'px '+-(x*96)+'px';
document.getElementById('gameBoard').appendChild(node);
}
}
}
根据 Goldie 的评论,我将 onclick 事件调整为事件侦听器。
document.getElementById("gameBoard").addEventListener("click",function(e) {
if (e.target && e.target.matches("div.cards")) {
console.log("Anchor element clicked! "+e.target.id);
} });```
解决方案
我用 mousemove 替换了点击监听器,它工作得很好。
document.getElementById("gameBoard").addEventListener("mousemove",function(e) {
if (e.target && e.target.matches("div.cards")) {
console.log("Element id: "+e.target.id);
}});
推荐阅读
- symfony - 尝试使用 Swiftmailer 加载类“Swift_Attachment”
- php - Quickbooks 错误:属性 IsProject 不存在。IPPCustomer 类
- omnet++ - 是否有可能在 Veins 中使用当前的夜间版本的 SUMO?
- java - 将数据从 Java 进程传递到 python 脚本
- plantuml - PlantUML,列重排
- tensorflow - Keras 自定义损失:我如何知道哪些模式对应于 y_pred 和 y_true?
- c - 无法在 C 中打开文件 - 在 C 中打开文件时出错
- python - 在一个图中绘制不同数据框的不同列作为散点图
- spring-boot - 没有服务层的springboot项目
- android - 在 Unity 应用程序中初始化 Firebase 时出现 Native NullPointerException