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
1.1k views
in Technique[技术] by (71.8m points)

html - JavaScript onclick requires two clicks

My problem is that when onclicktriggers the toggleNew function it's not executing but when I click the div a second time it's executing just as it should...

HTML:

<div id="aside_main">
    <div onclick="toggleNew();">click</div>
    content
</div>
<div id="aside_new">
    content
</div>

JS:

function toggleNew() {
   var e = document.getElementById('aside_main');
   var se = document.getElementById('aside_new');
   if(e.style.display == 'block') {
    e.style.display = 'none';
    se.style.display = 'block';
   } else {
    e.style.display = 'block';
    se.style.display = 'none';
   }
}

CSS:

#aside_main {
  display: block;
} 
#aside_new {
  display: none;
}

What is happening here and how can I make the function work the first time a user clicks the div?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This will not work properly because you are using following line inside 'div#aside_main' which is going to be hidden.

 <div onclick="toggleNew();">click</div>

Try keeping it outside like this-

<div onclick="toggleNew();">click</div>
 <div id="aside_main">
  content
 </div>
 <div id="aside_new">
  content2
</div>

Also in javascript it is not checking for 'e.style.display' first time in if condition.

Try using

    if(e.offsetWidth > 0 || e.offsetHeight > 0){
      e.style.display = 'none';
      se.style.display = 'block';
    }
    else
    {
      e.style.display = 'block';
      se.style.display = 'none';
    }

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

...