[英]Is there something better than using isTrusted to register a click on a Javascript animation?
I am making a game where I want to add to a score when a user clicks an element. 我正在制作一个我想在用户单击某个元素时添加到分数的游戏。 If the element is static, clicking adds one to the score, but when I add it to a JS animation, there is no predicting how many clicks register as true. 如果元素是静态的,则单击可将分数添加一个,但是当我将其添加至JS动画时,无法预测将多少次注册为true。 (Game at: https://hmcka.github.io/100days/day38/day38.html ) Is this happening because I am trying to have the click happen on an animation? (游戏位于: https : //hmcka.github.io/100days/day38/day38.html )发生这种情况是因为我试图让动画发生点击吗? Is there a better way to collect a click on animation? 有没有更好的方法来收集动画点击? I thought about inserting a setTimeout to add a pause after the initial click, but I think that this would be problematic if the user decides to click quickly several times. 我曾考虑过在初次点击后插入setTimeout来添加暂停,但是我认为如果用户决定快速点击几次,这将是有问题的。 The code I used for this feature is below. 我用于此功能的代码如下。
function bonk(e) {
if(!e.isTrusted) return;
score ++;
scoreBoard.textContent = score;
}
eventObject.isTrusted
tests to see if the user generated the action or code was written that did the action. eventObject.isTrusted
测试以查看用户是否生成了操作或编写了执行该操作的代码。 That's all it does. 这就是全部。 Client-side code can always be altered, so it doesn't actually prevent anything. 客户端代码始终可以更改,因此实际上并不能阻止任何事情。 It's just a way for your code to tell the difference. 这只是您的代码分辨差异的一种方法。
I believe the problem with your score being so high has to do with your animation. 我认为您得分太高的问题与动画有关。 Elements are overlapping each other, so technically you are clicking on Elements below the one you're clicking on. 元素彼此重叠,因此从技术上讲,您要单击要单击的元素下方的元素。 You need to make sure they are hitting the actual target, like: 您需要确保它们达到了实际目标,例如:
function bonk(e){
if(e.target === this){
scoreBoard.textContent = ++score;
}
}
After you do that, change your animation. 之后,请更改动画。
PS 聚苯乙烯
Although it won't kill your code, it looks there is no reason to return
anything within your frame
function, as well. 尽管它不会杀死您的代码,但看起来也没有理由在frame
函数内return
任何内容。 You can only return
a single value from a function (could be an Array or Object with multiple properties) and setInterval
's function argument doesn't need to receive a return
value. 您只能从函数中return
单个值(可以是具有多个属性的Array或Object),并且setInterval
的function参数不需要接收return
值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.