延遲菜單
獲取class兼容方法:
function getByClass(oParent, sClass) {
var aEle = oParent.getElementsByTagName('*');
var result = [] //最后返回数组
var re = new RegExp('\\b' + sClass + '\\b', 'i');//正则对象
for (var i = 0; i < aEle.length; i++) {
if (re.test(aEle[i].className)) {
result.push(aEle[i])
}
}
return result;
}
js代碼:
window.onload = function(){
var ul = document.getElementsByTagName('ul')[0]
var a = getByClass(document, 'normal')
var span1 = getByClass(document, 'float_layer');
var timer = null;
for (var i = 0; i < a.length; i++) {
a[i].index = i;
a[i].onmouseover = function () { //移到a.normal
for (var i = 0; i < a.length; i++) { //清除所有顯示
span1[i].style.display = 'none'
}
span1[this.index].style.display = 'block' //當前顯示
clearInterval(timer) //在a.normal上也須清除定時器
}
a[i].onmouseout = function () { //移開a.normal
var This = this
timer = setTimeout(function () {
span1[This.index].style.display = 'none' //this指setTimeout的對象window,改變this指向
}, 1000)
}
span1[i].onmouseover = function () { //在span.float_layer也顯示,所以需要清除timer
clearInterval(timer)
}
span1[i].onmouseout = function () { //離開span.float_layer,消失
var This = this;
timer = setTimeout(function () {
This.style.display = 'none'
}, 1000)
}
}
}