2017-12-05 13 views
0

イベントonclickに関する質問があります。私は研究中にこのコードを見つけました。私の質問です:テキストがすでに表示されているクリックの前でさえ、実際のボタンをクリックするまで、テキストを隠すことは可能ですか?そして、それ以上のオンクリックイベントを別々に行うことは可能ですか?divをクリックしてテキストを非表示にする

<html> 
 
<head> 
 
    <title>Show and hide div with JavaScript</title> 
 
    <script> 
 
    function showhide() 
 
    { 
 
      var div = document.getElementById("newpost"); 
 
    if (div.style.display !== "block") { 
 
     div.style.display = "block"; 
 
    } 
 
    else { 
 
     div.style.display = "none"; 
 
    } 
 
    } 
 
    </script> 
 
</head> 
 
<body> 
 
    <div id="newpost"> 
 
    <p>This div will be show and hide on button click</p> 
 
    </div> 
 
    <button id="button" onclick="showhide()">Click Me</button> 
 
</body> 
 
</html>

答えて

0

ありがとうdisplayプロパティのスタイルでどれもデフォルトでそれを作ります。

<div id="newpost" style="display:none"> 
    <p>This div will be show and hide on button click</p> 
    </div> 
1

はい。あなたのスタイルシートで#newpost div display: noneを持っていて、修飾子クラス.visibledisplay: blockで追加してください。最後に、あなたの関数であなたがclassList.toggle経由.visibleクラスを切り替えることができ、あなたが行くように良いことがあります:

var div = document.getElementById('newpost'); 
 

 
document.getElementById('button').addEventListener('click', showhide); 
 

 
function showhide() { 
 
    div.classList.toggle('visible'); 
 
}
#newpost { 
 
    display: none; 
 
} 
 

 
#newpost.visible { 
 
    display: block; 
 
}
<button id="button">Click Me</button> 
 

 
<div id="newpost"> 
 
    <p>This div will be show and hide on button click</p> 
 
</div>

+0

複数のonclickイベントを同じテーブル上にあるが異なるセルに配置することは可能ですか? –

+0

うん。あなたはあなたのセルをループする必要があり、ループ内でそれに応じてイベントリスナーを追加します。 –

0

はあなたのコードにこの単純なCSSを適用

div#newpost{ 
 
display: none; 
 
}

1

幸せなあなたがそうのようなボタンにクリックイベントで複数を追加することができますjQueryので:)

function showhide() { 
 
    var div = document.getElementById("newpost"); 
 
    div.classList.toggle('hidden'); 
 
}
.hidden{ 
 
display : none; 
 
}
<html> 
 
<head> 
 
    <title>Show and hide div with JavaScript</title> 
 
    
 
</head> 
 
<body> 
 
<!--if you want by default hidden then add class .hidden in new post --> 
 
    <div id="newpost" class="hidden"> 
 
    <p>This div will be show and hide on button click</p> 
 
    </div> 
 
    <button id="button" onclick="showhide()">Click Me</button> 
 
</body> 
 
</html>

0

コーディング:

 $("#button").on("click", function(){ 
 
     $("#newpost").toggle(); 
 
    }); 
 
     
 
    $("#button").on("click", function(){ 
 
     $("#secondpost").toggleClass("bold"); 
 
    });
#newpost{ 
 
    display:none; 
 
} 
 

 
.bold{ 
 
    font-weight:bold; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<html> 
 
<head> 
 
    <title>Show and hide div with JavaScript</title> 
 
</head> 
 
<body> 
 
    <div id="newpost"> 
 
    <p>This div will be show and hide on button click</p> 
 
    </div> 
 
    <button id="button">Click Me</button> 
 
    <p id="secondpost">toggle bold</p> 
 
</body> 
 
</html>

クリックで最初の上記の段落を切り替えます。 2回目のクリックは、太字にする最後の段落のクラスを切り替えます。