在加载页面时将活动状态更改为随机<li>



我在JS宾中有一个演示。

http://jsbin.com/ivigab/1/

我想做的很简单,我希望能够单击一个 li 并给它一个活动类,并让子div 淡入。如果可能的话,所有这些也会同时发生,同时用于以前的活动 li。

同样如标题所述,我想在每次用户查看页面时将活动 li 更改为随机,这可能吗?

这是一个

非常简单的例子,但应该给你想要的结果:-

$('#entries li').click(function() {
  // remove active class and fade div out from all list elements
  $('#entries li').removeClass('active');
  $('#entries div').fadeOut();
  // add active class to the clicked element and fade the div in
  $(this).addClass('active');
  $('div', this).fadeIn();    
});
// generate a random number ranging between 0 and the number of available li's
var random = Math.floor(Math.random() * $('#entries li').length);
// trigger the click event on the random element
$('#entries li').eq(random).trigger('click');

这是一个小提琴

看看这个它应该做你想做的事。

$(document).ready(function() {
  var $entries = $('#entries a');
  var randomNumber = Math.floor(Math.random()*$entries.length)
  $entries.click(function(e) {
    e.preventDefault();
    var $this = $(this);
    var $li = $this.parent();
    var activeEntry = $this.parents('#entries').find('li.active');
    activeEntry.find('div').fadeOut(300);
    activeEntry.removeClass('active');
    $li.find('div').fadeIn(300);
    $li.addClass('active');
  });
  $entries.eq(randomNumber).click();
});

最新更新