好吧,总是在我的脑海里这应该有用,但我是javascript的新手并且一次尝试了很多东西。这是一个导航栏,用于显示和隐藏div,同时在点击或悬停时更改导航颜色。好吧,它没有做到最后一部分。活动ID是当前显示的ID。对不起,我现在并不简单。
$(function () {
var active;
$('.selection').hide();
$('#homeDiv').show();
$('.navlink').hover(
function () {
$(this).css("color", "#806ac7");
},
function () {
if ($(this == active)) {
$(this).css("color", "#961014");
} else {
$(this).css("color", "#000000");
}
});
$('.navLink').click(function (e) {
active == $(this);
$('.navLink').css("color", "#000000");
$(this).css("color", "#961014");
$('.selection').hide();
$('#' + this.id + 'Div').show();
});
});
答案 0 :(得分:1)
除了我在问题评论中提到的内容之外,您还需要存储元素,而不是jQuery对象,并比较元素。
如果您尝试将不同来电的结果与$(this)
进行比较,则始终为false
,因为它们是唯一的对象。
$(function () {
var active;
$('.selection').hide();
$('#homeDiv').show();
$('.navlink').hover(
function () {
$(this).css("color", "#806ac7");
},
function () {
// RIGHT HERE, compare the element
if (this === active) {
$(this).css("color", "#961014");
} else {
$(this).css("color", "#000000");
}
});
$('.navLink').click(function (e) {
// RIGHT HERE, store the element
active = this;
$('.navLink').css("color", "#000000");
$(this).css("color", "#961014");
$('.selection').hide();
// Lowercase "D" in "div", and improved DOM selection
$(this).find('div').show();
});
});
答案 1 :(得分:0)
好像你错放了这一行的结束括号:if ($(this == active))
。它应该是if (this == active)
另外,您正在编写布尔值而不是设置变量:active == $(this)
应该是active = this;
答案 2 :(得分:0)
我认为最好的方法就是在用户点击导航项时添加一个类。在悬停处理程序中,检查类并相应地更改颜色。或者你可以简单地在css中使用重要来设置活动颜色,这样你就不需要在悬停中检查是否有效
$('.navLink').click(function (e) {
var $this = $(this);
$this.addClass('open').css("color", "#961014");
$('.navLink').css("color", "#000000");
$('.selection').hide();
$('#' + this.id + 'Div').show();
});
$('.navlink').hover(
function () {
$(this).css("color", "#806ac7");
},
function () {
var $this = $(this);
if ($this.hasClass('open') {
$this.css("color", "#961014");
} else {
$this.css("color", "#000000");
}
});
上面的解决方案是使用jquery来改变css颜色,但你可以在css中轻松完成。假设您的其余代码正常工作
答案 3 :(得分:0)
$(function () {
var active;
$('.selection').hide();
$('#homeDiv').show();
$('.navLink').hover(
function () {
$(this).css("color", "#806ac7");
},
function () {
if (active == this || active == undefined) {
$(this).css("color", "#961014");
} else {
$(this).css("color", "#000000");
}
});
$('.navLink').click(function (e) {
active = this;
$('.navLink').css("color", "#000000");
$(this).css("color", "#961014");
$('.selection').hide();
$('#' + this.id + 'Div').show();
});
});