randomly display a div class using JQuery

前端 未结 5 778
轻奢々
轻奢々 2020-12-08 17:28

I want to randomly display a div class using JQuery. The code is something like:

One
Two
相关标签:
5条回答
  • 2020-12-08 17:46

    Working example: jsFiddle

    js

    window.onload=function() {
      var E = document.getElementsByClassName("item");
      var m = E.length;
      var n = parseInt(Math.random()*m);
      for (var i=m-1;i>=0;i--) {
          var e = E[i];
          e.style.display='none';
      }
      E[n].style.display='';
    }
    

    js.minified

    window.onload=function(){var E=document.getElementsByClassName("item");var m=E.length;var n=parseInt(Math.random()*m);for(var i=m-1;i>=0;i--){var e=E[i];e.style.display='none';}E[n].style.display='';}
    

    html

    <div class="item">One</div>
    <div class="item">Two</div>
    <div class="item">Three</div>
    <div class="item">Four</div>
    <div class="item">Five</div>
    <div class="item">Six</div>
    <!-- Add as many as you want! //-->
    
    0 讨论(0)
  • 2020-12-08 17:47

    Something like that :

    $('.item').hide().eq(Math.floor(Math.random()*4)).show()
    

    Fiddle : http://jsfiddle.net/PPXmE/

    0 讨论(0)
  • 2020-12-08 17:50

    First we get a random int, from zero to the number of items (minus 1). Then we hide all other elements and show just the randomly chosen one.

    var random = Math.floor(Math.random() * jQuery('.item').length);
    jQuery('.item').hide().eq(random).show();
    

    Demo

    0 讨论(0)
  • 2020-12-08 17:51

    Use the setInterval function.

    Working example: http://jsfiddle.net/a0c0ntjc/

    setInterval(function(){
            var E=document.getElementsByClassName("item");
            var m=E.length;
            var n=parseInt(Math.random()*m);for(var i=m-1;i>=0;i--){
                var e=E[i];e.style.display='none';
            }
            E[n].style.display='';
    },3000);
    
    0 讨论(0)
  • 2020-12-08 18:04
    var number = Math.floor(Math.random()*3)
    var div = $(".item")[number];
    div.show();
    
    0 讨论(0)
提交回复
热议问题