2

我从另一个问题中抓取了这个片段:

<script type='text/javascript' >
$(document).ready(function () {
 $("div.content ul li a")
 .mouseover(function () {
  var t = $(this);
  if (!t.hasClass("clicked")) {  // very easy to check if element has a set of styles
   t.addClass('mouseover');
  }
 })
 .mouseout(function () {  // attach event here instead of inside mouse over
  $(this).removeClass('mouseover');
 });

 $("div.content ul li a").click(function () {
  var t = $(this);
  t.toggleClass("clicked");
  if (t.hasClass("clicked")) {
   t.removeClass('mouseover');
  } else {
   t.addClass('mouseover');
  }
 });
});
</script>

我想要的最后一件事是在单击另一个选项卡时恢复选项卡的正常 css。例如,当我单击 tab1 时,选项卡的 bgcolors 为白色,当我进入 Tab2 时,它变为黑色。.Tab1 变为白色,Tab2 变为黑色

<ul> 
 <li>
  <a href="#Tab1">Tab 1</a>
 </li>
 <li>
  <a href="#Tab2">Tab 2</a>
 </li>
</ul> 

假设这是 CSS 部分

ul li a {background-color: white;}
ul li a.mouseover {background-color: black;}
ul li a.mouseout {background-olor: white;}
ul li a.clicked {background-color: black;}
4

3 回答 3

8

您实际上可以为此大大简化您的 Javascript。这应该可以达到您想要的效果。

<script type="text/javascript">
    $(document).ready(function() {
        $("div.content ul li a")
         .mouseover(function() {
             $(this).addClass('mouseover');
         })
         .mouseout(function() {
             $(this).removeClass('mouseover');
         });

        $("div.content ul li a").click(function(e) {
            e.preventDefault(); //prevent the link from actually navigating somewhere
            $(this).toggleClass("clicked");
            $("div.content ul li a").not(this).removeClass("clicked"); //remove the clicked class from all other elements
        });
    });
</script>

此处的 Javascript 将执行以下操作:

  • 悬停链接时添加“鼠标悬停”类
  • 当您不再悬停链接时删除“鼠标悬停”类
  • 当您单击一个链接时,它将切换“单击”类并将其从可能具有该类的任何其他链接中删除 - 这会将您的其他选项卡恢复到它们的“正常”状态。
于 2010-09-19T14:11:49.193 回答
1

@wsanville

双击同一个标签的问题怎么办?

如果我在单击选项卡时从选项卡中删除了一个底部边框(指示选定的一个),那很好。但是当我再次单击它时,它应该保持原样(没有底部边框),但是由于切换,现在看起来您还没有选择选项卡,但您仍然在那里。

于 2011-01-21T09:24:28.983 回答
0

仅使用 CSS 就可以实现您正在寻找的内容:

ul li a {background-color: white;}
ul li a:hover {background-color: black;}
ul li a:focus {background-color: black;}

演示

于 2010-09-19T14:22:09.570 回答