简体   繁体   English

JavaScript同时运行具有多个元素的相同功能

[英]JavaScript run same function with multiple elements at the same time

I have a JavaScript function that looks like this: 我有一个JavaScript函数,如下所示:

function buttonClick()
{
    var numberPop = Math.floor((Math.random()*1000)+1);
    $( "#number-add-" + numberPop ).fadeOut(2000);
}

I have the ability to click a button that runs this function multiple times. 我可以单击多次运行此功能的按钮。 However, sometimes, I click it before the previous element that it affected faded out. 但是,有时,我会在它受影响的上一个元素消失之前单击它。 Because of that, the fading of the previous element stops in the middle. 因此,前一个元素的淡入停止在中间。

How can I make it so that this function can CONTINUE fading the previously affected elements WHILE fading the current element as well? 我如何才能使该函数在继续淡入当前元素的同时继续淡入先前受影响的元素? This way, multiple elements can be fading at the same time. 这样,多个元素可以同时消失。

Edit: 编辑:

This is the entire code: 这是完整的代码:

function buttonClick(subEvent)
{
    var numberPop = Math.floor((Math.random()*1000)+1);
    var mainEvent = subEvent ? subEvent : window.event;
    var div = document.getElementById('number');
    div.innerHTML = div.innerHTML + '<div class="number-pop" id="number-add-'+ numberPop +'" style="z-index:99; position:absolute;margin-top:'+ (mainEvent.screenY - 98) +'px;margin-left:'+ (mainEvent.screenX - 12) +'px;">'+ '+1' +'</div>';
    $( "#number-add-" + numberPop ).stop(true, false).animate({top: "+=-200", opacity:'0'}, 3000, 'linear');
}

It's hard to tell how to fix it without all of your code (HTML + JS) -- we can't see what the element with id "number" is. 在没有所有代码(HTML + JS)的情况下,很难说出如何解决它-我们无法看到ID为“ number”的元素是什么。 That said, it looks like you're just trying to append new HTML. 就是说,您似乎只是在尝试添加新的HTML。 So, replace this: 因此,替换为:

var div = document.getElementById('number');
div.innerHTML = div.innerHTML + '<div class="number-pop" id="number-add-'+ numberPop +'" style="z-index:99; position:absolute;margin-top:'+ (mainEvent.screenY - 98) +'px;margin-left:'+ (mainEvent.screenX - 12) +'px;">'+ '+1' +'</div>';

with this: 有了这个:

$('#number').append('<div class="number-pop" id="number-add-'+ numberPop +'" style="z-index:99; position:absolute;margin-top:'+ (mainEvent.screenY - 98) +'px;margin-left:'+ (mainEvent.screenX - 12) +'px;">'+ '+1' +'</div>');

That will add the new HTML without resetting existing elements. 这将添加新的HTML,而无需重置现有元素。

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

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