我有一个切换 div,它是众多切换 div 之一,我需要一个链接,可以在 div 打开时将 div 切换为一种颜色,并在单击页面上的另一个链接时返回到默认颜色。 这是我用来切换 div 的代码,它工作完美!当我添加常规 css 代码时,当单击另一个链接时,链接将保持为已访问链接的颜色。
function showonlyone(thechosenone) {
$('.newboxes').each(function (index) {
if ($(this).attr("id") == thechosenone) {
$(this).show(200);
} else {
$(this).hide(600);
}
});
}
如何添加到此代码块以在选择时将颜色设置为不同的颜色,并在选择另一个链接时将其更改回默认颜色...谢谢!
最佳答案
最简单的(在我看来)方法是使用 .addClass()
应用或删除类。和.removeClass()
。然后,您可以使用 CSS 格式化颜色和任何其他设置。
function showonlyone(thechosenone) {
$('.newboxes').each(function (index) {
if ($(this).attr("id") == thechosenone) {
$(this).addClass("highlight");
} else {
$(this).removeClass("highlight");
}
});
}
稍后在 CSS 中:
.highlight a { /* may need to format differently depending on your HTML structure */
color: #ff0000; /* red */
}
您还可以像这样简化代码:
function showonlyone(thechosenone) {
$('.newboxes.highlight').removeClass("highlight"); // Remove highlight class from all `.newboxes`.
$('#' + thechosenone ).addClass("highlight"); // Add class to just the chosen one
}
此代码将等待 DOM 加载,然后将“highlight”类应用于 <div class="newboxes">
的第一次出现。 :
$(document).ready( function(){
$(".newboxes:first").addClass("highlight");
// The :first selector finds just the first object
// This would also work: $(".newboxes").eq(0).addClass("highlight");
// And so would this: $(".newboxes:eq(0)").addClass("highlight");
// eq(n) selects the n'th matching occurrence, beginning from zero
})
关于JQuery 显示隐藏 div 链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16287539/