2016-09-09 4 views
0

학교 과제에 몇 가지 문제가 있습니다. 어쨌든, startInterval을 사용할 때 나중에 interval을 지울 수 있도록 intervalID를 지정합니다. 불행히도, 당신이 "이 광기를 멈추게"버튼을 누를 때 명확하지 않습니다. 왜 그런지 알아?clearInterval 문제 (jquery, javascript)

은 당신이 알아야 할

var intervalID; 
 
$('.gal').click(function() { 
 
    var photoID = jQuery(this).attr("id"); 
 
    alert(alerts[photoID]); 
 
}); 
 

 
var alerts = { 
 
    //row one 
 
    "1:1": "This animal is a penguin!", 
 
    "1:2": "This animal is a lion!", 
 
    "1:3": "This animal is a cat!", 
 
    "1:4": "This animal is a giraffe!", 
 
    //row two 
 
    "2:1": "Cool looking ancient building!", 
 
    "2:2": "Cool looking modern building!", 
 
    "2:3": "Cool building from dubai!", 
 
    "2:4": "Cool building by the water!" 
 
}; 
 

 
$("#stop").click(function() { 
 
    clearInterval(intervalID); 
 
}); 
 

 
$(window).load(function() { 
 
    animate(); 
 
}); 
 

 
function animate() { 
 
    intervalID = setInterval(function() { 
 
    var width = 25; 
 
    $(".gal").animate({ 
 
     'marginLeft': '-=25px' 
 
    }); 
 
    $(".gal").animate({ 
 
     'marginLeft': '+=25px' 
 
    }); 
 
    $("#title").animate({ 
 
     'marginLeft': '+=' + width + 'px' 
 
    }, "slow"); 
 
    $("#title").animate({ 
 
     'marginLeft': '-=' + width + 'px' 
 
    }, "slow"); 
 
    $("body").animate({ 
 
     'backgroundColor': 'lightyellow' 
 
    }, 1000); 
 
    $("body").animate({ 
 
     'backgroundColor': 'yellow' 
 
    }, 1000); 
 
    $("body").animate({ 
 
     'backgroundColor': 'orange' 
 
    }, 1000); 
 
    $("body").animate({ 
 
     'backgroundColor': 'red' 
 
    }, 1000); 
 
    $("body").animate({ 
 
     'backgroundColor': 'lightpink' 
 
    }, 1000); 
 
    $("body").animate({ 
 
     'backgroundColor': 'pink' 
 
    }, 1000); 
 
    $("body").animate({ 
 
     'backgroundColor': 'purple' 
 
    }, 1000); 
 
    $("body").animate({ 
 
     'backgroundColor': 'blue' 
 
    }, 1000); 
 
    $("body").animate({ 
 
     'backgroundColor': 'lightblue' 
 
    }, 1000); 
 
    $("body").animate({ 
 
     'backgroundColor': 'cyan' 
 
    }, 1000); 
 
    $("body").animate({ 
 
     'backgroundColor': 'green' 
 
    }, 1000); 
 
    $("body").animate({ 
 
     'backgroundColor': 'lightgreen' 
 
    }, 1000); 
 
    }, 0.1); 
 
}
body { 
 
    background-color: lightyellow; 
 
} 
 
#title { 
 
    display: block; 
 
    /*position:absolute;*/ 
 
} 
 
.gal { 
 
    display: block; 
 
    margin: 20px; 
 
    width: 250px; 
 
    height: 200px; 
 
    border: 5px solid black; 
 
} 
 
#stop { 
 
    position: fixed; 
 
    bottom: 0; 
 
    right: 0; 
 
    border: 3px solid red; 
 
}
<!DOCTYPE html> 
 
<html lang="en"> 
 

 
<head> 
 
    <title>JS Functions</title> 
 
    <meta charset="utf-8"> 
 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
 
    <script src="//cdn.jsdelivr.net/jquery.color-animation/1/mainfile"></script> 
 

 
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> 
 
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> 
 
    <link rel="stylesheet" type="text/css" href="styles.css"> 
 
</head> 
 

 
<body> 
 
    <div class="container-fluid"> 
 
    <button id="stop" class="btn-warning">Stop This Madness!</button> 
 
    <h1 id="title" style="margin-left: 20px;" class="text-primary">Image Gallery:</h1> 
 
    <div class="row"> 
 
     <div class="col-md-3"> 
 
     <img id="1:1" src="http://ngm.nationalgeographic.com/2012/11/emperor-penguins/img/02-airborne-penguin-exits-water_1600.jpg" class="gal"> 
 
     </div> 
 
     <div class="col-md-3"> 
 
     <img id="1:2" src="http://efdreams.com/data_images/dreams/lion/lion-03.jpg" class="gal"> 
 
     </div> 
 
     <div class="col-md-3"> 
 
     <img id="1:3" src="https://s3.graphiq.com/sites/default/files/stories/t2/tiny_cat_12573_8950.jpg" class="gal" /> 
 
     </div> 
 
     <div class="col-md-3"> 
 
     <img id="1:4" src="https://upload.wikimedia.org/wikipedia/commons/0/02/Giraffe_Ithala_KZN_South_Africa_Luca_Galuzzi_2004.JPG" class="gal"> 
 
     </div> 
 
    </div> 
 
    <div class="row"> 
 
     <div class="col-md-3"> 
 
     <img id="2:1" src="http://cdn.mos.cms.futurecdn.net/78b7453e70727aae7eed989ff2cee83d.jpg" class="gal" /> 
 
     </div> 
 
     <div class="col-md-3"> 
 
     <img id="2:2" src="http://thegrumpyoldlimey.com/images/buildings/dome_feature.jpg" class="gal" /> 
 
     </div> 
 
     <div class="col-md-3"> 
 
     <img id="2:3" src="https://d3dupjkkwlat3o.cloudfront.net/399433011453/2071971/576xN?1410992818" class="gal" /> 
 
     </div> 
 
     <div class="col-md-3"> 
 
     <img id="2:4" src="http://www.jazzhostels.com/blog/wp-content/uploads/2014/09/hemispheric-photo-valencia-spain-cc.jpg" class="gal"> 
 
     </div> 
 
    </div> 
 
    </div> 
 
    <script></script> 
 
    <script src="script.js"></script> 
 
</body> 
 

 
</html>

답변

1

두 가지 일반적인 포인트 (모든 배경 색상 물건에 대해 궁금해하는 경우에 나는 JQuery와 나는이 조각에 추가하지 않은 플러그인을 사용) :

  1. setInterval()의 지연을 밀리 초 단위로 지정, 당신은 012,303,210의 지연을 지정한- 즉, 초당 10000 번 실행되도록 함수를 예약하려고했습니다. 실제로 JS는 5ms 미만으로 가게하지 않습니다. 지정된 짧은 지연 시간은 반올림되지만 여전히 초당 약 200 회 실행됩니다.

  2. 당신이 .gal, #title로하고있는대로, 같은 요소에 .animate() 여러 번 호출

    body는, 현재의 사람이 마친 후 실행됩니다 추가로 애니메이션을 큐에.

5ms마다 5ms마다 코드에 여러 애니메이션이 큐에 추가됩니다. 각 애니메이션은 5ms보다 오래 걸립니다. 따라서 clearInterval()으로 전화를 걸어도 이미 많은 애니메이션이 대기 중이며 완료하는 데 오랜 시간이 걸립니다.

당신은 .stop() 방법을 사용하여 지정된 요소의 애니메이션 대기열을 애니메이션이 현재 진행 중지 및 삭제 할 수 있습니다

: 당신이 특히 경우,

$(".gal").stop(true); 

을하지만 setInterval() 항상 어설픈 조금 될 것입니다 사용하여 진행중인 애니메이션을 관리하려고 다른 시간이 지정된 여러 애니메이션. 다행히도 .animate() 메서드를 사용하면 애니메이션이 완료된 후에 실행할 콜백 함수를 제공 할 수 있으므로 거기에서 추가 처리를 예약 할 수 있습니다.

애니메이션을보다 효율적으로 관리 할 수있는 방법이 있는지에 대한 의견을 묻는 질문에 대한 답을 들었습니다. 배열을 사용하여 색상 변경을 제안한 다음 현재 색상 변경이 완료되면 .animate()을 다음 색상으로 다시 호출하십시오. 정렬.

어쩌면이 답변을 조금 더 짧게 만들기 위해 애니메이션과 관련이없는 일부 코드를 제거했으며 애니메이션 코드를 세 가지 기능으로 분리했습니다 각자가 무엇을하고 있는지 당신을 위해 그것을 명확하게하기 :

$("#stop").click(function() { 
 
    $(".gal, #title, body").stop(true); 
 
}); 
 

 
$(window).load(function() { 
 
    animateGallery(); 
 
    animateTitle(); 
 
    animateBody(); 
 
}); 
 

 
function animateGallery() { 
 
    $(".gal").animate({ 
 
    'marginLeft': '-=25px' 
 
    }, "slow").animate({ 
 
    'marginLeft': '+=25px' 
 
    }, "slow", animateGallery); // note the function set as final argument 
 
           // - it will be called when animation finishes 
 
} 
 

 
function animateTitle() { 
 
    var width = 25; 
 
    $("#title").animate({ 
 
    'marginLeft': '+=' + width + 'px' 
 
    }, "slow").animate({ 
 
    'marginLeft': '-=' + width + 'px' 
 
    }, "slow", animateTitle); // note the function set as final argument 
 
} 
 
    
 
var colors = ['lightyellow', 'yellow', 'orange', 'red', 'lightpink', 'pink', 'purple', 'blue', 'lightblue', 'cyan', 'green', 'lightgreen']; 
 
var currentColor = 0; 
 

 
function animateBody() { 
 
    $("body").animate({ 
 
    'backgroundColor': colors[currentColor] 
 
    }, 1000, animateBody); // note the function set as final argument 
 
    currentColor = (currentColor + 1) % colors.length; 
 
}
#title { display: block; } 
 
.gal { display: block; margin: 20px; width: 250px; height: 200px; border: 5px solid black; } 
 
#stop { position: fixed; z-index: 100; bottom: 0; right: 0; border: 3px solid red; }
<!DOCTYPE html> 
 
<html lang="en"> 
 
<head> 
 
    <title>JS Functions</title> 
 
    <meta charset="utf-8"> 
 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
 
    <script src="//cdn.jsdelivr.net/jquery.color-animation/1/mainfile"></script> 
 
</head> 
 
<body> 
 
    <div class="container-fluid"> 
 
    <button id="stop" class="btn-warning">Stop This Madness!</button> 
 
    <h1 id="title" style="margin-left: 20px;" class="text-primary">Image Gallery:</h1> 
 
    <div class="row"> 
 
     <div class="col-md-3"> 
 
     <img id="2:1" src="http://cdn.mos.cms.futurecdn.net/78b7453e70727aae7eed989ff2cee83d.jpg" class="gal" /> 
 
     </div> 
 
     <div class="col-md-3"> 
 
     <img id="2:2" src="http://thegrumpyoldlimey.com/images/buildings/dome_feature.jpg" class="gal" /> 
 
     </div> 
 
     <div class="col-md-3"> 
 
     <img id="2:3" src="https://d3dupjkkwlat3o.cloudfront.net/399433011453/2071971/576xN?1410992818" class="gal" /> 
 
     </div> 
 
     <div class="col-md-3"> 
 
     <img id="2:4" src="http://www.jazzhostels.com/blog/wp-content/uploads/2014/09/hemispheric-photo-valencia-spain-cc.jpg" class="gal"> 
 
     </div> 
 
    </div> 
 
    </div> 
 
</body> 
 
</html>

+0

당신이 생명의 은인입니다! – smod