我试图随机淡化span标签中包含的元素。 stackoverflow上有一些例子,但我不能让它们在我的代码中工作。
另外..有没有比在span标签中包装每个单词更优雅的方法?
我试图将akll的跨度转换为数组,然后随机选择该数组中的一个元素,并通过更改该元素的不透明度将其淡入,然后将其从数组中删除 这是myy尝试的一个方面..
https://jsfiddle.net/jnghna9s/2/
我的script.js:
$(document).ready(function() {
$("#contact").click(function() {
var spans = $("#changingP span").get();
for(var i =0; i < spans.length; i++) {
var index = Math.floor(Math.random() * spans.length);
$(spans[index]).fadeTo(200, 1, function() {
spans.splice(index,i);
}
})
});
});
答案 0 :(得分:2)
我会使用fadeTo
方法的完整回调。像这样的东西会起作用:
var spans = $('#changingP span').get();
function fadeIn() {
var index = Math.floor(Math.random() * spans.length);
$(spans[index]).fadeTo(200, 1, function() {
spans.splice(index, 1);
if (spans.length) {
fadeIn();
}
});
}
fadeIn();
span {
opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="changingP">
<span>Want </span><span>to </span><span>get </span><span>in</span><span> contact</span><span> with </span><span>me</span><span>?</span>
<br /><span>Email</span><span>: </span><span>edit</span><span>.</span><span>ed</span><span>email</span><span>@</span><span>gmail</span><span>.</span><span>com</span>
<br /><span>Link</span><span>edI</span><span>n</span><span>: </span><span>http</span><span>s://w </span><span></span><span>ww.</span><span>lin</span><span>kedi</span><span>n.com</span><span>/</span><span>in/</span><span>edit</span><span>ed</span><span>email</span>
</p>
答案 1 :(得分:1)
@dfsq答案很好。对于像我这样对jQuery-less版本感兴趣的极客,以下内容也是如此:(见fiddle)
function randomFade(elements) {
var shownCount = 0,
indexes = [];
function appear(el) {
setTimeout(function() {
var count = 10, i = setInterval(function() {
el.style.opacity = (parseFloat(el.style.opacity) || 0) + 0.1;
if (!count--)
clearInterval(i);
}, 50);
}, shownCount++*200);
}
function shuffle(o){
// from http://stackoverflow.com/questions/6274339/
// how-can-i-shuffle-an-array-in-javascript#answer-6274381
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i),
x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
for (var i = elements.length; i--;) indexes.push(i);
indexes = shuffle(indexes);
for (var f = indexes.length; f--;) appear(elements[indexes[f]]);
}
答案 2 :(得分:0)
您的for循环逻辑已关闭。试试这个
var maxDelay = 5000;
for(var i=0; i < $length; i++) {
var random = Math.ceil(Math.random() * maxDelay);
$('span')eq(i).delay(random).css("opacity","1");
}