簡體   English   中英

單擊后使div消失

[英]Make a div disappear after clicking on it

我使圓形div隨機掉落。 當我單擊一個圓時,我希望它消失並且我希望分數增加一。

這是我的代碼:

function CreateDiv() {
    var ranLeft1 = Math.floor((Math.random() * 700) + 1);
    var ranInterval = 1000 + Math.floor((Math.random() * 5000) + 1);
    jQuery('<div class="droper1" id="droper1" onclick="myFunction()" />').css({top: 20, left: ranLeft1 }).animate({top: "+=573px"}, 9000 ).appendTo('#container' );
    window.setTimeout( CreateDiv, ranInterval );
}

var score = 0;
document.getElementById("myBtn").addEventListener("click", myFunction);
function myFunction() {
    score++;
    //make the div dissapear after one click on it .. how ??!!
    document.getElementById("score").innerHTML = score;
}

您可以嘗試一下(注意:這是從內存中經過測試的)

function CreateDiv() {
    var ranLeft1 = Math.floor((Math.random() * 700) + 1);
    var ranInterval = 1000 + Math.floor((Math.random() * 5000) + 1);
    jQuery('<div class="droper1" onclick="myFunction()" />').css({top: 20, left: ranLeft1 }).animate({top: "+=573px"}, 9000 ).appendTo('#container' );
    window.setTimeout( CreateDiv, ranInterval );
}

var score = 0;

$(document).on("click", ".droper1", function() {
    score++;
    $("#score").innerHtml(score);
    $(this).remove();
});

您希望在單擊時remove() $(this) ,但是使用委托比將click方法直接分配給每個新生成的div更快:

var div_counter=0;
function CreateDiv() {
    var ranLeft1 = Math.floor((Math.random() * 700) + 1);
    var ranInterval = 1000 + Math.floor((Math.random() * 5000) + 1);
    jQuery('<div class="droper1" id="'+ ++div_counter +'" />').css({top: 20, left: ranLeft1 }).animate({top: "+=573px"}, 9000 ).appendTo('#container' );
    window.setTimeout( CreateDiv, ranInterval );
}

var score = 0;

$('body').on('click', '.droper1', function(){
   score++;
   $(this).remove();
});

這應該做您想要的Memo Awaw。

當我單擊一個圓時,我希望它消失並且我希望分數增加一。

下面的代碼在加載時會創建一個click函數。 單擊其中一個圓圈后,div會被刪除(但您也可以根據需要使用hide)。 分數增加一。 出於測試原因,我留在console.log()中,因此您可以選擇在檢查器中看到分數增加。

 jQuery(document).ready(function() { var score = 0; $('.foo').on('click', function() { jQuery(this).remove(); score++; console.log("New score is: " + score); }); }); 
 .foo { border-radius: 50%; width: 20px; height: 20px; background-color: blue; text-indent: -10000px; } .foo:hover { cursor: crosshair; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='foo' id=1>content</div> <div class='foo' id=2>content</div> <div class='foo' id=3>content</div> <div class='foo' id=4>content</div> 

$('#myBtn').on('click', function(){
     $('droper1').hide();
});

暫無
暫無

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

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