我试图为菜单项创建一个子菜单,我已经创建了一个项目列表并使用了一个鼠标悬停事件处理程序,但子菜单仍然存在。一旦鼠标离开子菜单div而不是标签div,我需要将其删除。鼠标悬停功能有效但鼠标输出有问题。我是新手使用javascript和DOM
这是代码(DOM):
var creatbtndiv = document.createElement("div");
var creatbtn = document.createElement("button");
creatbtn.innerHTML = "Click Me";
var creatlbl = document.createElement("label");
creatlbl.innerHTML = "Hover Over Me ";
creatbtndiv.appendChild(creatlbl);
creatbtndiv.appendChild(creatbtn);
document.body.appendChild(creatbtndiv);
var list = function () {
var creatDiv = document.createElement("div");
creatDiv.id = "submenudiv";
creatDiv.className = "submenudiv";
var creatul = document.createElement("ul");
for(index = 0; index < 5; ++index){
li = document.createElement("li");
li.className = "list";
li.innerHTML = "Submenu" + index;
creatul.appendChild(li);
}
creatDiv.appendChild(creatul);
document.body.appendChild(creatDiv);
};
//If the cursor hovers over the label, activate this function//
creatlbl.onmouseover = function () {
var alert = confirm("yes master");
list();
};
creatDiv.onmouseout = function(){
var confirm = confirm("the mouse is out");
list.removeChild(creatDiv);
};
答案 0 :(得分:0)
问题是&#39; creatDiv&#39;在鼠标悬停事件发生之前不存在,因此触发list()函数。
您无法将onmouseout事件附加到不存在的creatDiv。
建议更改:
var list = function () {
var creatDiv = document.createElement("div");
creatDiv.id = "submenudiv";
creatDiv.className = "submenudiv";
var creatul = document.createElement("ul");
for(index = 0; index < 5; ++index){
li = document.createElement("li");
li.className = "list";
li.innerHTML = "Submenu" + index;
creatul.appendChild(li);
}
creatDiv.appendChild(creatul);
document.body.appendChild(creatDiv);
creatDiv.onmouseout = function(){
document.body.removeChild( this )
};
};
但这仍然不太正确,因为当你在文本之间鼠标时div会消失,但这是另一个问题。
答案 1 :(得分:0)
creatDiv在其范围之外,所以这个函数什么都不做:
creatDiv.onmouseout = function(){
//var confirm = confirm("the mouse is out");
list.removeChild(creatDiv);
};
您可以在以下情况下使用此功能:
document.body.appendChild(creatDiv);
creatDiv.onmouseout = function(){
//var confirm = confirm("the mouse is out");
this.parentNode.removeChild(this);
};