2016-09-22 3 views
1

카운트 다운이 멋지게 작동하지만, 같은 페이지에서 여러 인스턴스를 필요로하는 단계에 있습니다. 내가 사용하고있는 스크립트는 온라인에서 발견되었으며 바로 자바 스크립트이지만 JavaScript는별로 좋지 않으므로 각 카운터를 고유하게 만드는 방법을 잘 모르겠습니다.여러 인스턴스를 사용할 때 카운트 다운 충돌

자바 스크립트 :

function calcage(secs, num1, num2) { 
    s = ((Math.floor(secs/num1))%num2).toString(); 
    if (LeadingZero && s.length < 2) 
    s = "0" + s; 
    return "<b>" + s + "</b>"; 
} 

function CountBack(secs) { 
    if (secs < 0) { 
    document.getElementById("cntdwn").innerHTML = FinishMessage; 
    return; 
    } 
    DisplayStr = DisplayFormat.replace(/%%D%%/g, calcage(secs,86400,100000)); 
    DisplayStr = DisplayStr.replace(/%%H%%/g, calcage(secs,3600,24)); 
    DisplayStr = DisplayStr.replace(/%%M%%/g, calcage(secs,60,60)); 
    DisplayStr = DisplayStr.replace(/%%S%%/g, calcage(secs,1,60)); 

    document.getElementById("cntdwn").innerHTML = DisplayStr; 
    if (CountActive) 
    setTimeout("CountBack(" + (secs+CountStepper) + ")", SetTimeOutPeriod); 
} 

function putspan(backcolor, forecolor) { 
document.write("<span id='cntdwn' style='background-color:" + backcolor + 
       "; color:" + forecolor + "'></span>"); 
} 

if (typeof(BackColor)=="undefined") 
    BackColor = "white"; 
if (typeof(ForeColor)=="undefined") 
    ForeColor= "black"; 
if (typeof(TargetDate)=="undefined") 
    TargetDate = "12/31/2020 5:00 AM"; 
if (typeof(DisplayFormat)=="undefined") 
    DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds."; 
if (typeof(CountActive)=="undefined") 
    CountActive = true; 
if (typeof(FinishMessage)=="undefined") 
    FinishMessage = ""; 
if (typeof(CountStepper)!="number") 
    CountStepper = -1; 
if (typeof(LeadingZero)=="undefined") 
    LeadingZero = true; 


CountStepper = Math.ceil(CountStepper); 
if (CountStepper == 0) 
    CountActive = false; 
var SetTimeOutPeriod = (Math.abs(CountStepper)-1)*1000 + 990; 
putspan(BackColor, ForeColor); 
var dthen = new Date(TargetDate); 
var dnow = new Date(); 
if(CountStepper>0) 
    ddiff = new Date(dnow-dthen); 
else 
    ddiff = new Date(dthen-dnow); 
gsecs = Math.floor(ddiff.valueOf()/1000); 
CountBack(gsecs); 

사용법 :

<script language="JavaScript"> 
TargetDate = "$variable"; 
BackColor = "palegreen"; 
ForeColor = "navy"; 
CountActive = true; 
CountStepper = -1; 
LeadingZero = true; 
DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds."; 
FinishMessage = "It is finally here!"; 
</script> 

어떤 도움에 감사드립니다.

답변

0

키는 모든 것을 로컬 범위로 가져 오는 것입니다. 가지고있는 모든 것이 전역 범위에 있으므로 하나의 인스턴스 만 허용됩니다. 함수의 모든 것을 랩핑하고 대신 객체를 만들어야합니다. setTimeOut 대신 setInterval도 사용했습니다. 마지막으로 html을 만들지 않는 기존 HTML 컨테이너 (동적 컨테이너를 만들고 페이지에 쓰는 document.write을 수행해야 함)에 대해 작업하려고합니다.

View Demo

HTML :

<!-- container 1 for a timer --> 
<div id="time1"></div> 
<!-- container 2 for a timer --> 
<div id="time2"></div> 
<script src="/js/script.js"></script> 
<script language="JavaScript"> 
// Create instance of your countdown with it's own settings 
var counterOne = new CountDown({ 
    // This is the id name for the container (<div id="time1"></div>) 
    send_to:'time1', 
    forecolor:'red', 
    targetdate:'09/22/2016 9:39 AM' 
}); 
// Create instance #2 with it's own settings 
var counterTwo = new CountDown({ 
    // This is the id name for the container (<div id="time2"></div>) 
    send_to:'time2', 
    forecolor:'blue', 
    targetdate:'09/22/2016 9:40 AM' 
}); 
// Apply the creation method 
// Without .create(), nothing will happen since all the working 
// script to apply the counter is in this method 
counterOne.create(); 
counterTwo.create(); 
</script> 

/js/script.js :

var CountDown = function(data) 
    { 
     // Assign this object 
     var thisObj = this; 
     // Make sure all settings are not left undefined 
     data.send_to  = (typeof data.send_to === "undefined")? "time1" : data.send_to; 
     data.backcolor  = (typeof data.backcolor === "undefined")? "white" : data.backcolor; 
     data.forecolor  = (typeof data.forecolor === "undefined")? "black" : data.forecolor; 
     data.targetdate  = (typeof data.targetdate === "undefined")? "12/31/2020 5:00 AM" : data.targetdate; 
     data.displayformat = (typeof data.displayformat === "undefined")? "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds." : data.displayformat; 
     data.countactive = (typeof data.countactive === "undefined")? true : data.countactive; 
     data.message  = (typeof data.message === "undefined")? "Ended" : data.message; 
     data.countstepper = (typeof data.countstepper != "number")? -1 : data.countstepper; 
     data.leadingzero = (typeof data.leadingzero === "undefined")? true : data.leadingzero; 
     // Get DOM object 
     var domObj   = document.getElementById(data.send_to); 

     this.calcage = function(secs, num1, num2) 
      { 
       var s = ((Math.floor(secs/num1))%num2).toString(); 

       if(data.leadingzero && s.length < 2) 
        s = "0" + s; 

       return "<b>" + s + "</b>"; 
      } 

     this.putSpan = function(backcolor, forecolor) 
      { 
       // Modify html instead of making html 
       domObj.style.backgroundColor = backcolor; 
       domObj.style.color    = forecolor; 
      } 

     this.writeBoard = function(secs,countDownEngine) 
      { 
       if(secs <= 0) { 
        clearInterval(countDownEngine); 
        domObj.innerHTML = data.message; 
        return; 
       } 

       var DisplayStr  = ''; 
       DisplayStr   = data.displayformat.replace(/%%D%%/g, thisObj.calcage(secs,86400,100000)); 
       DisplayStr   = DisplayStr.replace(/%%H%%/g, thisObj.calcage(secs,3600,24)); 
       DisplayStr   = DisplayStr.replace(/%%M%%/g, thisObj.calcage(secs,60,60)); 
       DisplayStr   = DisplayStr.replace(/%%S%%/g, thisObj.calcage(secs,1,60)); 
       domObj.innerHTML = DisplayStr; 
      } 

     this.create = function() 
      { 
       data.countstepper = Math.ceil(data.countstepper); 

       if(data.countstepper == 0) 
        data.countactive = false; 

       var SetTimeOutPeriod = ((Math.abs(data.countstepper)-1)*1000) + 990; 

       thisObj.putSpan(data.backcolor, data.forecolor); 

       var dthen = new Date(data.targetdate); 
       var dnow = new Date(); 
       var nowCalc = (data.countstepper > 0)? (dnow-dthen) : (dthen-dnow); 
       var ddiff = new Date(nowCalc); 
       var gsecs = Math.floor((ddiff.valueOf()/1000)); 

       var countDownEngine = setInterval(function() { 
        gsecs = gsecs+data.countstepper; 
        thisObj.writeBoard(gsecs,countDownEngine); 
       }, 1000); 
      } 
    } 
관련 문제