单击按钮后如何显示文本然后如果再次单击按钮,它将消失?

时间:2017-03-06 19:16:59

标签: javascript jquery html css

我正在为大学做一个分配任务的网站。无论如何,我创建了一个按钮并用CSS设置了它。我想要它,以便一旦用户点击按钮,它将显示文本,然后如果用户再次单击该按钮,它将消失。我尝试用Jquery编写代码(因为它更容易),但即使我认为它是正确的,它也没有按照我想要的方式显示在浏览器中。请帮忙



Jquery
$(document).ready(function() {
  $("Belfastbutton").click(function() {
    $("Belfastcontactdetails").toggle();
  });
});

#Belfastbutton {
  position: absolute;
  color: green;
  top: 310px;
  left: 130px;
  height: 40px;
  width: 120px;
  background-color: #e0e0d1;
  border-radius: 5px;
  padding: 5px;
}

#Belfastcontactdetails {
  color: green;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 id="Belfast">Belfast</h1>
<button id="Belfastbutton">Click for Details</button>
<p id="Belfastcontactdetails">
  34 Boucher Road, Belfast.
  <br> Co.Antrim
  <br> BT27
</p>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

选择按钮时,您只是错过了#,而

$(document).ready(function() {
  $("#Belfastbutton").click(function() {
    $("#Belfastcontactdetails").toggle();
  });
});
#Belfastbutton {
  position: absolute;
  color: green;
  top: 310px;
  left: 130px;
  height: 40px;
  width: 120px;
  background-color: #e0e0d1;
  border-radius: 5px;
  padding: 5px;
}

#Belfastcontactdetails {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 id="Belfast">Belfast</h1>
<button id="Belfastbutton">Click for Details</button>
<p id="Belfastcontactdetails">
  34 Boucher Road, Belfast.
  <br> Co.Antrim
  <br> BT27
</p>

答案 1 :(得分:0)

对于信息:

你也可以转发CSS:

&#13;
&#13;
[for="Belfastbutton"] {
  position: absolute;
  color: green;
  top: 310px;
  left: 130px;
  line-height: 40px;
  width: 120px;
  background-color: #e0e0d1;
  border-radius: 5px;
  padding: 0 5px;
  text-align:center;
  box-shadow:2px 2px 2px 1px gray;
  transition:0.05s;
 }
#Belfastcontactdetails {
color: green;
display:none;
}
#Belfastbutton:checked ~ #Belfastcontactdetails {
display:block;
}
/* hide input */
#Belfastbutton {position:absolute;
right:100vw;
}
/* add visual behavior to label */
[for="Belfastbutton"]:active { 
  box-shadow:-2px -2px 2px 1px gray;
}
&#13;
<h1 id="Belfast">Belfast</h1>
 <label for="Belfastbutton">Click for Details</label>
 <input type="checkbox" id="Belfastbutton"/>
 <p id="Belfastcontactdetails">
 34 Boucher Road, Belfast.
 <br> Co.Antrim
 <br> BT27
 </p>
&#13;
&#13;
&#13;