Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
523 views
in Technique[技术] by (71.8m points)

javascript - How can I hide a <div> and have it show only when a <textarea> has focus?

I'm using the same editor as Stack Overflow and the HTML looks something like this with multiple editors on a page:

<pagedown-admin id="modal-data-solution-1">
   <div>
      <div>
         Menu
      </div>
   </div>
   <textarea>
         ABC
   </textarea>
</pagedown-admin>
<pagedown-admin id="modal-data-solution-2">
   <div>
      <div>
         Menu
      </div>
   </div>
   <textarea>
         ABC
   </textarea>
</pagedown-admin>

Is there a way that I could hide the <div> that contains the menu and have it show only when the <textarea> has focus. Note that I'm not using jQuery so it would need to be a vanilla JavaScript solution. I'm just not sure where to start trying to code something like that.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could attach to the native event handlers a function like it is done in this question, and show/hide the menu.

(function() {
    var elm = document.getElementById("textarea");
    elm.addEventListener('blur', handler, false);
    elm.addEventListener('focus', handler, false);

    function handler(event) {
        if (event.type === "blur") {
            document.getElementById("menu").style.display = "none";
        }
        else {
            document.getElementById("menu").style.display = "";
        }
    }
})();
<pagedown-admin id="modal-data-solution-2">
   <div id="menu" style="display: none">
      <div>
         Menu
      </div>
   </div>
   <textarea id="textarea">
         ABC
   </textarea>
</pagedown-admin>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

[3] html - How to create even cell spacing within a

1.4m articles

1.4m replys

5 comments

57.0k users

...