我应该生成随机数的“div”,当我单击“div”时,我单击的“div”必须使用“fadeout”消失。 由于点击而显示和丢失的“div”数量将通过页面右上角显示的计数器进行计数。
下面的代码生成随机数的“div”,但我不知道如何使“div”消失以及如何计算消失的“div”。
我已经尝试过了
$("div").click(function()
{
$("div").fadeOut() ;
});
但是当我点击任意“div”时,页面中的所有“div”也会消失。我不希望所有“div”立即消失。我只希望我单击的“div”消失并进行计算。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<style>
#Counter
{
position: fixed ;
top: 0 ;
right: 0 ;
width: 300px ;
border: 3px solid grey ;
background-color: lightpink ;
}
</style>
</head>
<body onload = "followMouse();">
<div id = "Counter">Counter:</div>
<script>
$(document).ready(function()
{
var Min_Width, Max_Width, Min_height, Max_height ;
Min_Width = prompt("Please give the minimum width of div", "0") ;
Max_Width = prompt("Please give the maximum width of div" , "700") ;
Min_height = prompt("Please give the minimum height of div" , "0") ;
Max_height = prompt("Please give the maximum height of div" , "500") ;
function Random_Generator(Lower, Upper)
{
var Random_Number = Math.floor(Math.random() * (Upper - Lower + 1) ) ;
return Random_Number ;
}
function Div_Generator()
{
var dfrag = document.createDocumentFragment() ;
var count = Random_Generator(3, 200) ;
var Counter = 0 ;
for (var Counter = 0; Counter < count; Counter++)
{
var div = document.createElement("div") ;
dfrag.appendChild(div) ;
}
for (Counter = 0; Counter < dfrag.childNodes.length; Counter++)
{
div = dfrag.childNodes[Counter] ;
alterDivStyle(div) ;
}
document.body.appendChild(dfrag) ;
}
function rndColor()
{
var r = ('0' + Random_Generator(0,255).toString(16)).substr(-1),
g = ('0' + Random_Generator(0,255).toString(16)).substr(-1),
b = ('0' + Random_Generator(0,255).toString(16)).substr(-1) ;
return '#' + r + g + b ;
}
function alterDivStyle(div)
{
div.style.width = Random_Generator(Min_Width, Max_Width) + "px" ;
div.style.height = Random_Generator(Min_height, Max_height) + "px" ;
div.style.backgroundColor = rndColor() ;
div.style.color = rndColor() ;
div.style.position = "static" ;
div.style.float = "right" ;
div.style.border = '1px' ;
div.style.border = "solid";
div.style.borderColor = rndColor();
div.style.borderWidth = rndColor();
}
Div_Generator() ;
$("div").click(function()
{
$("div").fadeOut() ;
});
}) ;
</script>
</body>
</html>
最佳答案
使用
$(this).fadeOut()
获取点击时的目标div使用
:visible
和:hidden
选择器选择可见和隐藏的 div在
fadeOut()
回调函数中获取可见/隐藏div的数量,以获取效果完成后的数量
$("div").click(function(){
$(this).fadeOut(function(){
console.log($('div:hidden').length);
}) ;
});
Additional With dynamic generated divs you'll need to use
$(document).on('click' , 'div' , function(){
instead of$("div").click(function(){
关于javascript - 如何使变量 "Counter"计算随机创建并通过单击消失的 "div' s 的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55557753/