我正在编写一些vanilla JavaScript来创建一个很好的导航菜单.我坚持要添加一个活跃的类.
我按类名获取元素而不是id.如果用id替换下面的代码,但是,我需要它应用于多个元素.
HTML
<img class="navButton" id="topArrow" src="images/arrows/top.png" />
<img class="navButton" id="rightArrow" src="images/arrows/right.png" />
Run Code Online (Sandbox Code Playgroud)
JS
var button = document.getElementsByClassName("navButton");
button.onmouseover = function() {
button.setAttribute("class", "active");
button.setAttribute("src", "images/arrows/top_o.png");
}
Run Code Online (Sandbox Code Playgroud)
请不要包含jQuery的答案.
moh*_*han 44
document.getElementsByClassName返回节点列表.因此,您必须遍历列表并将事件绑定到单个元素.像这样...
var buttons = document.getElementsByClassName("navButton");
for(var i = 0; i < buttons.length; ++i){
buttons[i].onmouseover = function() {
this.setAttribute("class", "active");
this.setAttribute("src", "images/arrows/top_o.png");
}
}
Run Code Online (Sandbox Code Playgroud)
在您的代码段中,button是一个实例NodeList,您不能直接附加事件侦听器,也不能直接更改元素的className属性.
您最好的选择是委派活动:
document.body.addEventListener('mouseover',function(e)
{
e = e || window.event;
var target = e.target || e.srcElement;
if (target.tagName.toLowerCase() === 'img' && target.className.match(/\bnavButton\b/))
{
target.className += ' active';//set class
}
},false);
Run Code Online (Sandbox Code Playgroud)
当然,我的猜测是,active一旦mouseout事件触发就需要删除该类,您可以考虑使用第二个委托者,但您也可以将事件处理程序附加到具有active该类的一个元素:
document.body.addEventListener('mouseover',function(e)
{
e = e || window.event;
var oldSrc, target = e.target || e.srcElement;
if (target.tagName.toLowerCase() === 'img' && target.className.match(/\bnavButton\b/))
{
target.className += ' active';//set class
oldSrc = target.getAttribute('src');
target.setAttribute('src', 'images/arrows/top_o.png');
target.onmouseout = function()
{
target.onmouseout = null;//remove this event handler, we don't need it anymore
target.className = target.className.replace(/\bactive\b/,'').trim();
target.setAttribute('src', oldSrc);
};
}
},false);
Run Code Online (Sandbox Code Playgroud)
使用此代码有一些改进的余地,但我不会在这里获得所有乐趣;-).
| 归档时间: |
|
| 查看次数: |
127969 次 |
| 最近记录: |