gpt4 book ai didi

javascript - 根据Jquery中的条件选择随机值

转载 作者:行者123 更新时间:2023-11-28 18:19:17 26 4
gpt4 key购买 nike

请看下面的html

<div class="testclass" style="top:30px;">msg1</div>
<div class="testclass" style="top:60px;">msg2</div>
<div class="testclass" style="top:80px;">msg3</div>
<div class="testclass" style="top:100px;">msg4</div>
<div class="testclass" style="top:200px;">msg5</div>

选择小于623的随机值,并且该随机值不在元素的停止样式中,即不在30,60,80,100,200中。但是这些值会发生变化。并且该随机值需要距离最高值至少多 30。这个怎么做.

最佳答案

<!DOCTYPE html>
<html>
<head>
<title>hello</title>
</head>
<body>

<div class="testclass" style="top:30px;">msg1</div>
<div class="testclass" style="top:60px;">msg2</div>
<div class="testclass" style="top:80px;">msg3</div>
<div class="testclass" style="top:100px;">msg4</div>
<div class="testclass" style="top:200px;">msg5</div>

<button>Generate Random number</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<script>

function isNotValid(arr, val){ // checks if the random value is valid
var check = false;

$.each(arr, function(v){
if(val < (v+30)){
check = true;
return;
}
});

return check;
}

function getRandomNum(max, min) { // getting random value
return parseInt(Math.random() * (max - min) + min);
}

$(document).ready(function(){
$("button").click(function(){
var topValues = [];

$(".testclass").each(function(){ // stores [30, 60, 80, 100, 200] in topValues variable
topValues.push(parseInt($(this).css('top')));
});

var randomValue = 0;

do{
randomValue = getRandomNum(623, 0); // max, min for fetching random value. You can pass the smallest topValues as min to optimize the process
} while(isNotValid(topValues, randomValue)); // fetch random value until its not valid


alert(randomValue); // alert random value
});
});

</script>

</body>

以上是完整的工作代码,但还可以更加完善。我相信这会对您有所帮助:)

关于javascript - 根据Jquery中的条件选择随机值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40213545/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com