我正在建立一个网站,其中有一个介绍性部分,其中说明了“我是[角色]”。我想要做的是声明一个角色列表(即网页设计师,用户体验开发人员,图形设计师等),并让[role]中的文字自动循环显示每个角色。
类似于:
HTML:
<p>Hi there I'm a <span id="role"></div>.</p>
jQuery的:
$(document).ready(function(){
$('#role').html('web designer').delay(400).html('graphic designer')
.delay(400).html('UX developer');
});
我知道这是一个解决方案,但我如何通过首先声明一个“角色”列表然后让html循环通过列表来实现这一目标呢?
由于
答案 0 :(得分:4)
使用setInterval()和数组操作
尝试一个简单的解决方案jQuery(function($){
var roles = ['role 1', 'role 2', 'role 3'];
//used to determine which is the next roles to be displayed
var counter = 0;
var $role = $('#role')
//repeat the passed function at the specified interval - it is in milliseconds
setInterval(function(){
//display the role and increment the counter to point to next role
$role.text(roles[counter++]);
//if it is the last role in the array point back to the first item
if(counter >= roles.length){
counter = 0;
}
}, 400)
})
演示:Fiddle
答案 1 :(得分:0)
Fiddle is here解决方案。
$(document).onReady( function () {
var roles = [ 'web designer', 'graphic designer', 'UX developer' ];
var roleId = 0;
window.setInterval(function () {
$('#role').html(roles[roleId]);
roleId = roleId + 1;
if(roleId >= roles.length) { roleId = 0; }
}, 1000);
});
我使用setInterval()使列表不断重复,但这当然是可选的。您可以将角色定义为数组,并在计时器上迭代它们。如果你只想循环一次for for循环。