Have weird problem with something I'm working on.
For reference here is the code: JSFIDDLE LINK
Just a recap of the flow:
Now the thing I'm missing, is a way to loop through all the divs in the span--and randomly start to change the opacity on each span to 0. This needs to be done in a completely random order--but needs to stop once all spans have been looped through.
I have some code for the math below--but I'm not exactly sure why its not working.
var min = 1;
var max = 400;
var paras = $('#main span');
var random = Math.floor(Math.random() * (max - min + 1)) + min;
paras.hasClass('number' + random).addClass('change');
Can anyone assist me with the math--or help me come up with another solution, I'm sure the effect will look great if its working.
Thanks!
You can always select only the remaining span
element without the change
class.
function randomChange() {
var paras = $('#main span:not(.change)');
var min = 0;
var max = paras.length - 1;
var random = Math.floor(Math.random() * (max - min + 1)) + min;
$(paras.get(random)).addClass('change');
if (paras.length > 1) setTimeout(randomChange, 5);
}
We can make it more efficient if we search for the unchanged spans only once and remove the changed items from the array.
var paras = $('#main span:not(.change)');
function randomChange() {
var min = 0;
var max = paras.length - 1;
var random = Math.floor(Math.random() * (max - min + 1)) + min;
$(paras.get(random)).addClass('change');
// Remove from item from the array
paras.splice(random, 1);
console.log("Chose: "+ random + " Out: " + max);
if (paras.length > 0) setTimeout(randomChange, 5);
}
.hasClass不是选择器,您需要选择要更改的span元素:
$('#main span.number'+random).addClass("change");
You might be over-engineering it. See this fiddle
$(document).ready(function() {
$('p').each(function(){
var spans = $(this).text().split(' ');
$p = $("<p></p>");
$.each(spans, function(index, value) {
$p.append($("<span>"+value+" </span>"));
});
$(this).replaceWith($p);
});
$("#main span").each(function(index) {
var r = Math.floor(Math.random() * 2000);
$(this).delay(r).fadeTo('slow', 0);
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.