簡體   English   中英

如何使此淡入/淡出無限?

[英]How do I make this fade in/out infinite?

當start變量為true時,此代碼淡入和淡出div #shape。 當我從事件“單擊”調用“開始”方法時,瀏覽器停止工作,因為while內部方法是不定式的,“單擊”事件直到“開始”方法完成后才結束。 我希望該方法在“ click”事件完成后運行。 我該怎么辦?

CSS

#shape {
     background-color:red;
     width:100px;
     height:100px;
     display:none;
 }

HTML

 <div id="shape"></div>
    <button id="startButton">start game!</button>

JS

var start = false;
$("#startButon").click(function () {
    start = true;
    startGame();
});

function startGame() {
    while (start == true) {
        $("#shape").fadeIn(1000).delay(1000).fadeOut(1000);
    }
}

您不需要標志,只需創建一個遞歸函數即可。 我將時間更改為300毫秒,因此您可以更輕松地看到它

http://jsfiddle.net/zfbptz9c/

$("#startButton").click(function () {
    startGame();
});

function startGame() {
    $("#shape").fadeIn(300, function () {
        $("#shape").fadeOut(300, function () {
            startGame();
        });
    });
}

div將淡入,並在淡入完成后淡出,然后再次調用startGame函數,整個過程將無限重復。

另外,僅當您只需要定位現代瀏覽器時,才可以使用css來實現。 我將把這個小提琴鏈接放在這里,它來自另一個問題。 我不會粘貼代碼,因為您沒有使用CSS標記問題,但是小提琴顯示了所有內容。 我對此不承擔任何責任。

如何使用CSS 3過渡創建循環的淡入/淡出圖像效果?

http://jsfiddle.net/FTLJA/261/

JavaScript在單線程環境中運行,這意味着一旦進入無限循環,就只能從其中退出循環。 在同步執行中,就像您在此處執行的那樣,循環外的任何代碼都不會影響循環條件。

就您的問題而言,人們提出了一些解決方案,例如進行遞歸函數或使用CSS3過渡。

另一種可能的方式是使用計時功能,例如setTimeout和/或setInterval

在下面的代碼中,每隔一秒鍾,單擊“開始”按鈕之后,直到單擊“停止”按鈕,都會使淡入/淡出發生。

 var toggle = true; // flag for animation direction var shape = $("#shape"); // so we don't select the shape each time we animate var duration = 1000; // animation duration var delay = 1000; // delay between animations var timerId; // timer id returned by setInterval // start animating the shape after the delay $("#startButton").click(function() { timerId = setInterval(animate, delay); }); // stop animating the shape and hide it $("#stopButton").click(function() { clearInterval(timerId); shape.css('display', 'none'); }); // function that animates the shape depending on the toggle flag function animate() { if (toggle) { shape.fadeIn(duration); toggle = false; } else { shape.fadeOut(duration); toggle = true; } } 
 #shape { background-color: red; width: 100px; height: 100px; display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="shape"></div> <button id="startButton">start game!</button> <button id="stopButton">stop game!</button> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM