我試圖創建一個後滾動器,上下移動容器以顯示下一篇文章。移動的類型(用動畫完成)取決於諸如下一篇文章是否是最後一篇文章以及文章大小是否大於查看容器等因素。用於滾動文章的jQuery自調用函數迭代
我以前使用了函數的setInterval,但發現我無法修改依賴於提及的變量的間隔時間。
相反,我選擇了函數迭代中的函數,這應該允許更多的靈活性。但它不起作用!我有一個完全註釋JSFiddle。
除了把代碼在這裏:
jQuery(document).ready(function ($) {
// An array of HTML elements with the class '.scrNote' (scrolling note)
var postArr = $('.scrNote');
// nextSec prepares the script on how to prepare
var nextSec = 0;
// Not sure if this is necessary, but tells us the starting position
var currPos = $('.postContainer').offset().top;
// topSpace tells the script how far to scroll
var topSpace = currPos + $(postArr[nextSec]).outerHeight(true);
function scrollPosts() {
nextSec++;
if (nextSec >= postArr.length) {
// A reset takes place, bring the posts back to the top
$('.widgPost').scroll();
$('.widgPost').animate({
scrollTop: 0
}, 2000);
nextSec = 0;
topSpace = currPos + $(postArr[nextSec]).outerHeight(true);
// A 4s delay takes place, before the function repeats (calling itself)
setTimeout(scrollPosts, 4000);
} else if (postArr[(nextSec - 1)].height() > $('widgPost').height) {
// A slow scroll takes place when the post is larger than the widget
$('.widgPost').scroll();
$('.widgPost').animate({
scrollTop: topSpace
}, 10000);
topSpace = currPos + $(postArr[nextSec]).outerHeight(true);
// The function begins again as normal, without a delay
scrollPosts();
} else {
// A regular scroll takes place
$('.widgPost').scroll();
$('.widgPost').animate({
scrollTop: topSpace
}, 3000);
topSpace = currPos + $(postArr[nextSec]).outerHeight(true);
// A 4s delay takes place, before the function repeats (calling itself)
setTimeout(scrollPosts, 4000);
}
}
// The function should be called here
scrollPosts();
});
.widgPost h1, h2, h3 {
margin: 0;
}
.widgPost {
width: 100%;
height: 150px;
position: relative;
overflow-y: hidden;
}
.postContainer {
height: 100%;
width: 100%;
}
.scrNote {
width: 100%;
min-height: 100px;
background: yellow;
position: relative;
display:block;
margin: 0 0 16px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="widgPost">
<div class="postContainer">
<div class="scrNote">
<h1>Hello!</h1>
Hello here is some text</div>
<div class="scrNote">
<h1>Next post!</h1>
Hello here is some more text...</div>
<div class="scrNote">
<h1>Next new post!</h1>
Hello here is some more text...</div>
</div>
</div>
感謝您的幫助!
jQuery文檔事實上要求[height()](http://api.jquery.com/height/)。不知道爲什麼這工作至今,但謝謝你! –
@JackWeatherilt ..它肯定會**,如果你用'$'**包裝你的'postArr' ..檢查這個** [DEMO](https://jsfiddle.net/Guruprasad_Rao/b7vtrwpc/3/)* *太.. :) –
問題是postArr的其中一個高度函數和缺少選擇器後缺少一組括號。我想糾正你說**。height()絕對是一個函數**。您的解決方案初始解決方案實際上是一個快速解決方案,瀏覽器會忽略它。 –