使用 jQuery 模拟悬停

2022-01-22 00:00:00 hover jquery css

鉴于现有的按钮"

HTML:

 <div id="MB">
    <ul class="list">
       <li id="post-5"><a href="#post-5">5</a></li>
       <li id="post-4"><a href="#post-4">4</a></li>
       <li id="post-3"><a href="#post-3">3</a></li>
       <li id="post-2"><a href="#post-2">2</a></li>
       <li id="post-1"><a href="#post-1">1</a></li>
    </ul> 
 </div>

CSS:

  #MB .list li a {
        float:left;
        color:#333;
        background:#f6f6f6;
        border:1px solid #eaeaea;
        border-right:none;
        padding:0 8px;
        }

   #MB .list li a:hover,
   #MB .list li a:focus {
        color:#fff;
        border:1px solid #333333;
        border-right:none;
        background:#404040;
        text-decoration:none;
        }

我想每隔 n 秒按顺序在每个按钮上自动模拟悬停".

I'd like to simulate "hover" automatically on each button, sequentially, every n seconds.

这意味着每 n 秒一个按钮悬停"(改变颜色等),在下一个间隔关闭",下面的按钮将打开"等等......

This means that every n seconds a button is "hovered" (changing color etc), at next interval is "turned off" and the following button will "turn on" and so on...

推荐答案

#MB .list a:hover,
#MB .list a:focus,
#MB .list .active a {
  /* hover styles */
}

(我已经稍微简化了您的选择器,我还建议尝试删除外部 div 因为这些通常是不必要的,单独的 ul 就足够了)

(I've simplified your selectors a bit, I would also suggest trying to remove the outer div as these are often unnecessary and the ul alone is enough)

Javascript 悬停:

Javascript hover:

function setHover() {
    if ($('#MB .list .active').next().length) {
        $('#MB .list .active').next().addClass('active').end().removeClass('active');
    } else {
        $('#MB .list .active').removeClass('active');
        $('#MB .list li:first-child').addClass('active');
    }
}

setInterval(setHover, 1000);

相关文章