2016-10-24 2 views
0

смотрите следующий HTMLвыбрать случайное значение, основанное на состоянии в Jquery

<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 больше от верхних значений. Как это сделать .

ответ

3
<!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> 

Выше полный рабочий код, но он может быть более полируется. Я уверен, что это вам поможет :)

+0

Спасибо. Работает. – Dan

+0

больше всего приветствуется :) –

Смежные вопросы