你绝对应该使用CSS来改变悬停形象。更不用提的是,您可以在悬停上添加类,或使用CSS和JavaScript的组合来实现相同的效果。但是,如果您需要单独使用JavaScript,我会推荐使用jQuery或其他具有这些方法和其他许多内置库的库。尤其是如果你对纯JavaScript不太熟练的话。
CSS
此选项消除了图像标签完全的需要。为了确保图像正确显示,您需要为CSS中的LI元素提供维度,并使A元素显示:block。
#ourteam li a { display: block; }
#ourteam li:nth-child(1) a { background: url('/img/avatars/avatar1.png'); }
#ourteam li:hover:nth-child(1) a { background: url('/img/avatars/avatar11.png'); }
#ourteam li:nth-child(2) a { background: url('/img/avatars/avatar_t.png'); }
#ourteam li:nth-child(3) a { background: url('/img/avatars/avatar3.png'); }
#ourteam li:hover:nth-child(3) a { background: url('/img/avatars/avatar3h.png'); }
#ourteam li:nth-child(4) a { background: url('/img/avatars/avatar4.png'); }
#ourteam li:hover:nth-child(4) a { background: url('/img/avatars/avatar4h.png'); }
jQuery的
这将处理所有3个事件 - 点击鼠标进入和鼠标离开。它只是交换“src”和“data-other-src”的值。
$(function(){
$('#ourteam img').on('click mousenter mouseleave', function(e){
e.preventDefault();
var _this = $(this),
oldSrc = _this.attr('src'),
newSrc = (_this.attr('data-other-src')) ? _this.attr('data-other-src') : oldSrc;
_this.attr('src', newSrc).attr('data-other-src', oldSrc);
});
});
或者,我们可以使用悬停,然后单击事件触发的主动类要么列表项或者一个。对于这个例子,我们来看看锚点。
CSS
#ourteam li:nth-child(1) a { background: url('/img/avatars/avatar1.png'); }
#ourteam li:nth-child(1) a.active { background: url('/img/avatars/avatar1h.png'); }
#ourteam li:nth-child(2) a { background: url('/img/avatars/avatar_t.png'); }
#ourteam li:nth-child(2) a.active { background: url('/img/avatars/avatar_t.png'); }
#ourteam li:nth-child(3) a { background: url('/img/avatars/avatar3.png'); }
#ourteam li:nth-child(3) a.active { background: url('/img/avatars/avatar3h.png'); }
#ourteam li:nth-child(4) a { background: url('/img/avatars/avatar4.png'); }
#ourteam li:nth-child(4) a.active { background: url('/img/avatars/avatar4h.png'); }
jQuery
$(function(){
$('#ourteam li a').on('click mousenter mouseleave', function(e){
e.preventDefault();
$(this).toggleClass('active');
});
});