简体   繁体   中英

Javascript onblur/onfocus

I am having some trouble with the two events, they work fine, however I have ran into a problem: I have a div inside of a div. When the inner div is in focus, I want a set of style buttons to be appended to the outer div. However when i try to click on the buttons, it unfocuses the inner div and makes the buttons go away. I want them to go away when focus is lost but I dont want focus to be lost when I press a button. Sorry if this is a little confusing here is some code and a jsfiddle of it in action:

function addButtons() {
  var node = document.createElement('div');
  var obj = document.getElementById('container');
  node.setAttribute('id', 'buttons');
  node.innerHTML = '<input type="button" value="B" onClick="document.execCommand(\'bold\',false)" />';
  obj.appendChild(node); 
}

function removeButtons(id) {
  var obj = document.getElementById('container');
  obj.removeChild(obj.childNodes[3]);
}

http://jsfiddle.net/bnjGE/2/

If I remove the removeButtons() function, it works fine, but multiple buttons will be created.

I can try to clear things up, just ask.

Thankyou

You can add a return false; statement on the mousedown event on the button, f.ex:

node.getElementsByTagName('input')[0].onmousedown = function(e) {
    return false;
};

http://jsfiddle.net/bnjGE/8/

document.onclick = function(e){
    console.log(e.target);
    if(e.target.id != 'buttons' && e.target.parentNode.id != 'buttons' && e.target.id != 'textarea'){
        removeButtons();
    }
}​

http://jsfiddle.net/bnjGE/7/ Maybe this is a solution,but not perfect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM