我试图一次显示一个div并一遍又一遍地滚动它们。我修改了一个我发现的小提琴,我把它放在小提琴上,但由于某种原因,我不能用小提琴实现一个简单的测试页面。它根本不会滚动div。
这是小提琴:http://jsfiddle.net/Twistar/d6nZP/86/
这是我实现的代码:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="styles/styles.css">
<script type="text/javascript" src="includes/headers/jquery.min.js"></script>
<script type="text/javascript">
function go() {
var visibleBox = $('#container .boxes:visible');
visibleBox.hide();
var nextToShow = $(visibleBox).next('.boxes:hidden');
if (nextToShow.length > 0) {
nextToShow.show();
} else {
$('#container .boxes:hidden:first').show();
}
return false;
}
setInterval(go, 1000);
</script>
</head>
<body>
<div id="container">
<div class="boxes" style="display:">first box</div>
<div class="boxes" style="display:none;">second box</div>
<div class="boxes" style="display:none;">third box</div>
<div class="boxes" style="display:none;">forth box</div>
</div>
</body>
有谁能告诉我我做错了什么?
答案 0 :(得分:2)
我可能只是简单地做到这样:http://jsbin.com/osepim/1/
$(function() {
// hide all and show first
$(".boxes").hide().first().show();
setInterval(function(){
moveNext();
}, 1000);
});
function moveNext() {
var box = $(".boxes:visible"),
nextBox = box.next();
if(nextBox.length === 0)
nextBox = $(".boxes:first");
//hide all
$(".boxes").hide();
// show next
nextBox.fadeIn();
}
答案 1 :(得分:2)
I am guessing that you have a working fiddle but on your local test page its not working
你的小提琴是有效的,因为你从左边的下拉菜单中选择了默认的处理程序,而且它在你的测试页面上没有工作,因为你的jquery处理程序丢失了。
原因是you are missing the document ready handler here
:
$(function(){
setInterval(go, 1000);
});
尝试替换这个,看看是否有帮助。
答案 2 :(得分:2)
您需要使用准备好的事件$(document).ready()
包装您的javascripts代码或使用简短版本$()
,这只会在页面加载完成后执行代码,因此您的代码应该类似于
$(function(){
function go() {
var visibleBox = $('#container .boxes:visible');
visibleBox.hide();
var nextToShow = $(visibleBox).next('.boxes:hidden');
if (nextToShow.length > 0) {
nextToShow.show();
} else {
$('#container .boxes:hidden:first').show();
}
return false;
}
setInterval(go, 1000);
});
答案 3 :(得分:1)
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="styles/styles.css" />
<style type="text/css">.boxes{display:none}</style>
</head>
<body>
<div id="container">
<div class="boxes">first box</div>
<div class="boxes">second box</div>
<div class="boxes">third box</div>
<div class="boxes">forth box</div>
</div>
<script type="text/javascript" charset="utf-8" src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
function go() {
var visibleBox = $('#container .boxes:visible'); // GET THE DIV
visibleBox.hide();
var nextToShow = $(visibleBox).next('.boxes:hidden');
if (nextToShow.length > 0) { // SHOW NEXT ITEM
nextToShow.show();
} else {
$('#container .boxes:hidden:first').show();
}
return false;
}
setInterval(go, 1000); // MS SECOND OF LOOP
</script>
</body>
</html>