我遇到了麻烦,我的代码是(简化的):
$(document).ready(function() {
var theta = 0;
carouselNext = function() {
theta += 1;
}
var carouselInterval = window.setInterval(carouselNext, 1000);
var spinning = true;
$("#stopstart").click.function() {
if (spinning) {
clearInterval(carouselInterval);
spinning = false;
} else {
carouselInterval = setInterval(carouselNext, CAROUSEL_DURATION);
spinning = true;
}
}
编辑:这是我的代码的完整版本
var CAROUSEL_DURATION = 5000;
var html = '';
$(document).ready(function(){
$.getJSON("/static/js/users.json", function(data){
$.each(data, function(index, student){
html += '<div class="student">';
html += '<h2>' + student.level + ' of the Month</h2>';
html += '<h4>' + student.firstname + ' ' + student.lastname + '</h4>';
html += '<p>' + student.class + '</p></br>';
html += '</div>';
});
$('.students').html(html);
$('.students').cycle({
fx: 'fade',
pause: '1',
prev: '#prev',
next: '#next',
speed: '500',
timeout: 10000
});
// catch JSON reading error
}).fail( function(d, textStatus, error) {
console.error("getJSON failed, status: " + textStatus + ", error: "+error)
});
$(".my-btn").click(function() {
$('<li>').text("click").prependTo('.posts');
});
var carousel = document.getElementById('carousel');
var navButtons = document.querySelectorAll('#navigation button');
var panelCount = carousel.children.length;
var transformProp = Modernizr.prefixed('transform');
var theta = 0;
$("#next").on('click', function() {
theta += ( 360 / panelCount ) * -1;
carousel.style[ transformProp ] = 'translateZ( -288px ) rotateY(' + theta + 'deg)';
});
carouselNext = function() {
theta += ( 360 / panelCount ) * -1;
carousel.style[ transformProp ] = 'translateZ( -288px ) rotateY(' + theta + 'deg)';
}
var carouselInterval = window.setInterval(carouselNext, CAROUSEL_DURATION);
var spinning = true;
// stop carousel spinning
$("#stop-start").click(function() {
if (spinning) {
clearInterval(carouselInterval);
spinning = false;
} else {
carouselInterval = setInterval(carouselNext, CAROUSEL_DURATION);
spinning = true;
}
})
// clicking on carousel navigation buttons
onNavButtonClick = function( event ) {
var increment = parseInt( event.target.getAttribute('data-increment') );
theta += ( 360 / panelCount ) * increment * -1;
carousel.style[ transformProp ] = 'translateZ( -288px ) rotateY(' + theta + 'deg)';
};
for (var i=0; i < 2; i++) {
navButtons[i].addEventListener( 'click', onNavButtonClick, false);
}
});
当我加载页面时,theta正在按预期每秒加1:
当我点击“stopstart”按钮时,theta会停止滴答,正如所料......
然而,当我再次点击“stopstart”时,theta返回NaN。我不明白为什么会这样。我出错的任何想法?
答案 0 :(得分:2)
感谢@gillesc提供的有用评论 - #stop-stort位于#navigation内部,导致onNavButtonClick与carouselNext同时被触发,导致
increment = parseInt( event.target.getAttribute('data-increment') );
失败并将theta变成NaN。