简体   繁体   English

如何使div下降可点击?

[英]How to make falling div clickable?

I've made words in falling div, example of my code is here: 我在div降级中做了字,我的代码示例在这里:

http://jsfiddle.net/apHLu/674/embedded/result/ http://jsfiddle.net/apHLu/674/embedded/result/

But I can't understand why I can't make words in div's clickable. 但是我不明白为什么我不能在div的clickable中添加文字。 Sometimes I can click it and I see alert message with word, but sometimes I should click the above word to see alert message. 有时我可以单击它,然后看到带有单词的警报消息,但有时我应该单击上面的单词以查看警报消息。 Maybe it is because this animation way is very slow? 也许是因为这种动画方式非常慢?

Main part of my code: 我的代码的主要部分:

/* Start by creating a wrapper div, and an empty img element */
var leafDiv = document.createElement('div');
var image = document.createElement('div');

/* Randomly choose a leaf image and assign it to the newly created element */
image.innerHTML = phrase[counter];
image.style.padding = "40px 0 0 20px";

leafDiv.style.backgroundColor = "#eee";
leafDiv.setAttribute('data-url', counter);
leafDiv.setAttribute('data-text', phrase[counter]);

leafDiv.onclick = function () {
    alert($(this).attr('data-text'));
};


leafDiv.style.top = "-100px";

i edited your fiddle and solved it here: http://jsfiddle.net/apHLu/675/ 我编辑了您的小提琴,并在此处解决了该问题: http : //jsfiddle.net/apHLu/675/

/*    
    // YOUR OLD METHOD
    leafDiv.onclick = function () {
        alert($(this).attr('data-text'));
    };
*/

// MY SUGGESTION
leafDiv.addEventListener('mouseup', function() {
    alert($(this).attr('data-text'));
});

binding click events on animated dom elements is a bit tricky, and as you see, it's difficult to "catch" them. click事件绑定到动画dom元素上有些棘手,而且如您所见,很难“捕获”它们。

in these cases it's much better to bind mousedown or mouseup . 在这些情况下,最好绑定mousedownmouseup in this case i think mouseup is preferred. 在这种情况下,我认为mouseup是首选。

take a look and see if it's what you meant. 看一看,看看这是否是您的意思。

hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM