Я пытаюсь создать кнопку, которая скрывает информацию и показывает информацию. Весь контент находится в теге. Есть две проблемы с этим кодом.
1. You have to click the button twice to reveal information.
2. When information is revealed the pictures don't align like it should.. it gets moved to the middle then the right.
Как я могу исправить эти проблемы..?
$(document).ready(function() {
$("#toggle").click(function() {
var elem = $("#toggle").text();
if (elem == "More News >") {
//Stuff to do when btn is in the read more state
$("#toggle").text("Read Less");
$("#text").slideDown();
} else {
//Stuff to do when btn is in the read less state
$("#toggle").text("More News >");
$("#text").slideUp();
}
});
});
#text{
display:none;
}
.btn-container{
margin: auto;
height:44px;
width:166.23px;
}
button{
user-select:none;
-webkit-user-select:none;
-moz-user-select:none;
-ms-user-select:none;
cursor:pointer;
border: solid 1px;
padding:8px;
font-size:1em;
background: transparent;
color:black;
box-sizing:border-box;
}
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2 style = "text-align:center;" > All Stories</h2>
<hr> </hr>
<div class = "smallSpacer">
<div class = "row">
<div class = "col-sm-6" style = "text-align:left;">
<p class = "#" style = "color:lightgray; ">Jan, 01, 2019 </p>
<small>Title of the news article will be diplayed under the photo. </small>
</div>
<div class = "col-sm-6" style = "text-align: right;">
<img src = "/images/news1.jpg" style = "height:200px; width:300px; ">
</div>
</div>
<hr> </hr>
<div class = "row">
<div class = "col-sm-6" style = "text-align:left;">
<p class = "#" style = "color:lightgray; ">Jan, 01, 2019 </p>
<small>Title of the news article will be diplayed under the photo. </small>
</div>
<div class = "col-sm-6" style = "text-align: right;">
<img src = "/images/news2.jpg" style = "height:200px; width:300px; ">
</div>
</div>
<hr> </hr>
<div class = "row">
<div class = "col-sm-6" style = "text-align:left;">
<p class = "#" style = "color:lightgray; ">Jan, 01, 2019 </p>
<small>Title of the news article will be diplayed under the photo. </small>
</div>
<div class = "col-sm-6" style = "text-align: right;">
<img src = "/images/news3.jpg" style = "height:200px; width:300px; ">
</div>
</div>
<hr> </hr>
<div class = "smallSpacer">
<div>
<br>
<span id = "text">
<div class = "row">
<div class = "col-sm-6" style = "text-align:left;">
<p class = "#" style = "color:lightgray; ">Jan, 01, 2019 </p>
<small>Title of the news article will be diplayed under the photo. </small>
</div>
<div class = "col-sm-6" style = "text-align: right;">
<img src = "/images/news2.jpg" style = "height:200px; width:300px; ">
</div>
</div>
<hr> </hr>
<div class = "row">
<div class = "col-sm-6" style = "text-align:left;">
<p class = "#" style = "color:lightgray; ">Jan, 01, 2019 </p>
<small>Title of the news article will be diplayed under the photo. </small>
</div>
<div class = "col-sm-6" style = "text-align: right;">
<img src = "/images/news3.jpg" style = "height:200px; width:300px; ">
</div>
</div> <br>
</div>
<div class = "btn-container">
<button id = "toggle"> More News > </button>
</div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<div class = "bigSpacer"></div>
</span>
</section>
Ожидается: кнопка должна плавно отображать информацию одним щелчком мыши, а изображения должны выравниваться по правому краю.
На самом деле: есть сбой, и вам нужно дважды щелкнуть, чтобы открыть информацию, а изображения выравниваются по правому краю после того, как они сначала переместятся в центр страницы.
К сожалению, я не в данный момент.
Причина, по которой ваш первый щелчок не регистрируется, вероятно, заключается в том, что точный текст в вашем html <button id = "toggle"> More News > </button>
отличается от вашего кода jquery $("#toggle").text("More News >");
Поэтому при первом нажатии срабатывает оператор else, назначающий кнопку «Дополнительные новости >», затем он переключается туда после.
Чтобы исправить это, вы можете добавить атрибут к кнопке переключения.
<button id = "toggle" toggle = "expand">More News ></button>
а затем используйте следующее:
if ($("#toggle").attr("toggle") === "expand") {
$("#text").css("display", "inline");
$("#toggle").attr("toggle", "shrink");
}
Я добавил это в код файла main.js, когда я нажимаю кнопку, он работает нормально. Кнопка работает одним щелчком мыши, и изображения выравниваются правильно. Но затем снова появляется кнопка «Дополнительные новости», и если я нажимаю ее, она меняется на «Меньше читать», и все снова дает сбой, и фотографии не выравниваются должным образом.
$(document).ready(function() { $("#toggle").click(function() { var elem = $("#toggle").text(); if (elem == "Больше новостей >" ) { // Что нужно сделать, когда кнопка находится в состоянии «Читать больше» $("#toggle").text("Read Less"); $("#text").slideDown(); } else { //Что нужно сделать делать, когда btn находится в состоянии «меньше чтения» ("toggle") === "expand") { $("#text").css("display", "inline"); $("#toggle").attr("toggle", "shrink") ; } }); });
это то, что я добавил, это то, что вы имели в виду!
Вам нужно добавить оператор else туда. В противном случае он не будет текст другого случая. else { $("#text").css("display", "none"); $("#toggle").attr("toggle", "expand"); }
Теперь кнопка неактивна, а текст не появляется и не скрывается.
$(document).ready(function() { $("#toggle").click(function() { var elem = $("#toggle").text(); if (elem == "Больше новостей >" ) { // Что нужно сделать, когда кнопка находится в состоянии «Читать больше» $("#toggle").text("Read Less"); $("#text").slideDown(); } else { //Что нужно сделать делать, когда btn находится в состоянии «меньше чтения» ("toggle") === "expand") { else { $("#text").css("display", "none"); $("#toggle").attr("toggle", "expand "); } };
Привет, @tsharma, у тебя есть JSFiddle/codepen/etc твоего проекта?