Изменение порядка отображения элементов после нажатия события — javascript

#javascript

#язык JavaScript

Вопрос:

После того, как я нажму на кнопку «Рассчитать», под ней появится кнопка «Сброс», но я хочу изменить стили отображения, как они оба отображаются после события щелчка. Я хочу, чтобы они стояли бок о бок, а не друг на друге (картинка в ссылке представляет идею). Я попытался сделать это, переключив класс после щелчка, но таким образом я мог изменить только один внешний вид элемента. Как бы это лучше всего сделать? Пример заказа кнопок

HTML-код

 lt;div class="container"gt;  lt;headergt;  lt;div class="h1-background"gt;  lt;h1 class="h1"gt;Tip calculatorlt;/h1gt;  lt;/divgt;  lt;/headergt;  lt;div class="text"gt;    lt;pgt;How much was your bill?lt;/pgt;  lt;form name="theForm3"gt;  lt;input class="input-bill" placeholder="Bill Amount $"gt;  lt;pgt;How big tip will you give?lt;/pgt;  lt;!-- DROP DOWN--gt;  lt;div class="select"gt;  lt;select class="percents"gt;  lt;option value="1"gt;Nothinglt;/optiongt;  lt;option value="0.5"gt;5%lt;/optiongt;  lt;option value="0.10"gt;10%lt;/optiongt;  lt;option value="0.15"gt;15%lt;/optiongt;  lt;option value="0.20"gt;20%lt;/optiongt;  lt;option value="0.30"gt;30%lt;/optiongt;    lt;/selectgt;  lt;/divgt;  lt;/formgt;  lt;!-- AFTER DROP DOWN--gt;  lt;pgt;How many people are sharing the bill?lt;/pgt;  lt;input class="input-people" placeholder="Number of people"gt;  lt;button onclick="calculateTip(), changeStyle()" class=" button center button-calc"  type="button"gt;Calculate  lt;/buttongt;    lt;button onclick="" class=" button center reset-button" type="button"gt;Reset  lt;/buttongt;  

КОД JS

 "use strict"; const buttonCalc = document.querySelector(".button-calc"); function calculateTip() {  //Selectors  const inputBill = document.querySelector(".input-bill").value;  let inputPeople = document.querySelector(".input-people").value;  const percents = document.querySelector(".percents").value;  //Event listeners   //validate input  if (inputBill === "" || percents == 0) {  alert("Please enter values");  return;  }     //Check to see if this input is empty or less than or equal to 1  if (inputPeople === "" || inputPeople lt;= 1) {  inputPeople = 1;   document.querySelector(".each").style.display = "none";   } else {  document.querySelector(".each").style.display = "block";  }    //Functions  let total = (inputBill * percents) / inputPeople;  console.log(total);  //round to two decimal places  total = Math.round(total * 100) / 100;  //next line allows us to always have two digits after decimal point  total = total.toFixed(2);  //Display the tip   // Display alert i there is no TIP  if (percents == 1) {  alert(`There is no tip, you must pay only the bill ${total}`)  return;  }    document.querySelector(".reset-button").style.display = "block";  document.querySelector(".totalTip").style.display = "block";  document.querySelector(".tip").innerHTML = total;  }   function changeStyle() {  let container = document.querySelector(".container");  container.style.height = "400px";  event.preventDefault(); }   //Hide the tip amount on load document.querySelector(".reset-button").style.display = "none"; document.querySelector(".totalTip").style.display = "none"; document.querySelector(".each").style.display = "none";  

Ответ №1:

Если я правильно понял ваш вопрос, создайте еще один div для этих кнопок, а затем попробуйте включить гибкий дисплей.

Ответ №2:

Поместите кнопки в контейнер, подобный этому, а затем переключите класс между «строкой действия» и «столбцом действий», чтобы получить желаемый результат,

 lt;div id="actions" class="actions-row"gt;  lt;button onclick="calculateTip(), changeStyle()" class=" button center button-calc"  type="button"gt;Calculate  lt;/buttongt;    lt;button onclick="" class=" button center reset-button" type="button"gt;Reset  lt;/buttongt;  lt;/divgt;  

затем в вашей функции calculateTip добавьте эту строку для переключения между классами:

 document.getElementById("actions").className = "actions-row";  

а затем в поле скрыть сумму чаевых при загрузке добавьте:

 document.getElementById("actions").className = "actions-column";  

Затем в вашем css создайте следующее:

 .actions-row{  display: flex;   flex-direction: row;   flex-wrap: nowrap; }  .actions-column{  display: flex;   flex-direction: column;   flex-wrap: nowrap; }