代码如下:
function getElementWidth(objectId) {x = $_(objectId);return x.offsetWidth;}
function getElementHeight(objectId) {x = $_(objectId);return x.offsetHeight;}
function getAbsoluteLeft(objectId) {
o = $_(objectId)
oLeft = o.offsetLeft
while(o.offsetParent!=null) {
oParent = o.offsetParent
oLeft += oParent.offsetLeft
o = oParent
}
return oLeft
}
function getAbsoluteTop(objectId) {
o = $_(objectId)
oTop = o.offsetTop
while(o.offsetParent!=null) {
oParent = o.offsetParent
oTop += oParent.offsetTop
o = oParent
}
return oTop
}
var showMenuDelay = 0;
function showMenu(showID,thisID){
clearTimeout(showMenuDelay);
$_(showID).style.display='';
var clickElementx = getAbsoluteLeft(thisID);
var clickElementy = getAbsoluteTop(thisID) + getElementHeight(thisID);
$_(showID).style.top = clickElementy + 'px';
$_(showID).style.left = clickElementx + 'px';
document.body.insertBefore($_(showID),document.body.firstChild);
$_(thisID).onmouseout = function(){closeMenu(showID);}
$_(showID).onmouseover = function(){clearTimeout(showMenuDelay);}
$_(showID).onmouseout = function(){closeMenu(showID);}
}
function hideMenu(showID){
$_(showID).style.display='none';
}
function closeMenu(showID){
showMenuDelay = setTimeout(function(){hideMenu(showID);},200);
}
使用方法<a href="#" onmouseover="showMenu('menuDiv','thidID')" id="thisID">菜单</a>
<div id="menuDiv"></div>
function getElementWidth(objectId) {x = $_(objectId);return x.offsetWidth;}
function getElementHeight(objectId) {x = $_(objectId);return x.offsetHeight;}
function getAbsoluteLeft(objectId) {
o = $_(objectId)
oLeft = o.offsetLeft
while(o.offsetParent!=null) {
oParent = o.offsetParent
oLeft += oParent.offsetLeft
o = oParent
}
return oLeft
}
function getAbsoluteTop(objectId) {
o = $_(objectId)
oTop = o.offsetTop
while(o.offsetParent!=null) {
oParent = o.offsetParent
oTop += oParent.offsetTop
o = oParent
}
return oTop
}
var showMenuDelay = 0;
function showMenu(showID,thisID){
clearTimeout(showMenuDelay);
$_(showID).style.display='';
var clickElementx = getAbsoluteLeft(thisID);
var clickElementy = getAbsoluteTop(thisID) + getElementHeight(thisID);
$_(showID).style.top = clickElementy + 'px';
$_(showID).style.left = clickElementx + 'px';
document.body.insertBefore($_(showID),document.body.firstChild);
$_(thisID).onmouseout = function(){closeMenu(showID);}
$_(showID).onmouseover = function(){clearTimeout(showMenuDelay);}
$_(showID).onmouseout = function(){closeMenu(showID);}
}
function hideMenu(showID){
$_(showID).style.display='none';
}
function closeMenu(showID){
showMenuDelay = setTimeout(function(){hideMenu(showID);},200);
}
使用方法<a href="#" onmouseover="showMenu('menuDiv','thidID')" id="thisID">菜单</a>
<div id="menuDiv"></div>
本文介绍如何使用JavaScript实现菜单的显示与隐藏功能,包括获取元素的位置、设置元素的位置和大小,以及处理鼠标悬停事件。代码示例中包含了使用DOM操作获取元素位置和大小的方法,以及利用setTimeout和clearTimeout进行延迟关闭菜单的功能。
954

被折叠的 条评论
为什么被折叠?



