我看到你最终选择了一个答案,但是我想加入我的两分钱,因为我用一个长的解释做了这个例子。我希望这对你的理解有所帮助。
第一个例子有一个计时器变量,使得每次更改都可以重置你的10秒计时器。这样,点击具有你的类名的元素也会重置计时器。
旁注:在下面的例子中,我使用 .on() 。如果您使用的是 jQuery 1.7 之前的版本,则可以将 .on() 替换为 .live()。
var tmrShowHide; // this variable will act as out timer for keeping up with time changes
// if you don't want to reset the 10 seconds everytime there is a change,
// then please see exmple 2
function divShowHide() { // this will be the method used to change the colors and reset the timer
clearTimeout(tmrShowHide); // clears previous timer so 10 seconds is reset
// the .toggle method will simply toggle the visible state (display in css) of the element it's called upon
// so if we start with one hidden and one visible, then this is all that is needed to make the change!
// also note that i'm calling both elements at once, as they'll both undergo the "toggle" change
$('#pf-blue-area, #pf-orange-area').toggle();
tmrShowHide = setTimeout(divShowHide, 10000); // resets timer to 10 seconds
}
$(function() { // Same as $(document).ready(function() { // just shorter!
// the following establiches our click event on the 2 class types
$(document).on('click', '.dab, .pfs', divShowHide);
// this will begin the timer and give us a variable that can be cleared as needed
tmrShowHide = setTimeout(divShowHide, 10000);
})
所以没有注释的话,它就很简单:
var tmrShowHide;
function divShowHide() {
clearTimeout(tmrShowHide);
$('#pf-blue-area, #pf-orange-area').toggle();
tmrShowHide = setTimeout(divShowHide, 10000);
}
$(function() {
$(document).on('click', '.dab, .pfs', divShowHide);
tmrShowHide = setTimeout(divShowHide, 10000);
})
下一个示例要短得多,因为它不会重置计时器,因此,单击类元素以进行更改将不会阻止其每10秒更改一次。
function divShowHide(e) { // this will be the method used to change the colors
// the .toggle method will simply toggle the visible state (display in css) of the element it's called upon
// so if we start with one hidden and one visible, then this is all that is needed to make the change!
// also note that i'm calling both elements at once, as they'll both undergo the "toggle" change
$('#pf-blue-area, #pf-orange-area').toggle();
}
$(function() { // Same as $(document).ready(function() { // just shorter!
// the following establishes our click event on the 2 class types
$(document).on('click', '.dab, .pfs', divShowHide);
// this will begin the unstoppable 10 second timer
setInterval(divShowHide, 10000);
})
所以没有注释的话,它就很简单:
function divShowHide(e) { $('#pf-blue-area, #pf-orange-area').toggle(); }
$(function() {
$(document).on('click', '.dab, .pfs', divShowHide);
setInterval(divShowHide, 10000);
})
jQuery(document).ready(function( $ )
? 这段代码意味着在文档加载时运行 jQuery 函数。$
符号是 jQuery 的缩写,通过将$
作为参数传递给函数,我们可以在函数内部将$
指定为 jQuery 对象。使用两个jQuery(document).ready
函数可能是为了确保所有的 jQuery 文件都已经加载并准备就绪。 - Deepak IngolesetInterval
可能更合适,因为它可以每10秒更改一次。 - msturdy