문제

I'm trying to create a submenu for a menu item, i have got as far as creating a list of items and using a mouseover event handler but the submenu just remains there. i need it to be removed once the mouse clears away from the submenu div, not the label div. The mouseover function works but the mouseout im having a problem with. I am new to using javascript and DOM

This is the code (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);
};
도움이 되었습니까?

해결책

creatDiv its outside its scope, so this function does nothing:

creatDiv.onmouseout = function(){
    //var confirm = confirm("the mouse is out");
    list.removeChild(creatDiv);
};

You could put this function, after:

document.body.appendChild(creatDiv);

creatDiv.onmouseout = function(){
    //var confirm = confirm("the mouse is out");
    this.parentNode.removeChild(this);
};

다른 팁

The issue is that 'creatDiv' doesn't exist until the mouseover event occurs, and thus triggers the list() function.

You cannot attach the onmouseout event to the nonexistent creatDiv.

Suggested change:

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 )
  };

};

This will still be not quite right, though, because the div will go away when you mouse between text, but that's another issue.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top