Можно ли использовать массив для querySelectorAll? - PullRequest
0 голосов
/ 01 апреля 2020

Я хочу, чтобы этот переключатель поменял текст между месячной и годовой ценой. Я считаю, что это лучше всего работает с использованием querySelectorAll, однако, так как мне нужно, чтобы это было сделано в трех разных местах, единственный способ найти это - написать ниже. Могу ли я выбрать все необходимые промежутки, используя массив, поскольку у меня есть другие отрезки на странице, которые мне не нужно выбирать? Или вы могли бы помочь мне, чтобы я мог уточнить этот код?

function mouseToggleSwitch() {
  var checkBox = document.getElementById("myCheck");
  var month = document.querySelectorAll("span")[1];
  var year = document.querySelectorAll("span")[2];
  var proMonth = document.querySelectorAll("span")[3];
  var proYear = document.querySelectorAll("span")[4];
  var masterMonth = document.querySelectorAll("span")[5];
  var masterYear = document.querySelectorAll("span")[6];


  if (checkBox.checked == true) {
    month.style.display = "block";
    year.style.display = "none";
    proMonth.style.display = "block";
    proYear.style.display = "none";
    masterMonth.style.display = "block";
    masterYear.style.display = "none";
  } else {
    month.style.display = "none";
    year.style.display = "block";
    proMonth.style.display = "none";
    proYear.style.display = "block";
    masterMonth.style.display = "none";
    masterYear.style.display = "block";
  }

}
.display-4 {
  font-size: 2rem;
  font-weight: 700;
  color: hsl(233, 13%, 49%);
  font-family: Montserrat, sans-serif;
}


/******* TOGGLE SWITCH *******/

.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
  margin: 0 20px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: linear-gradient(to right, hsl(236, 72%, 79%), hsl(237, 63%, 64%));
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked+.slider {
  background-image: linear-gradient(to right, hsl(236, 72%, 79%), hsl(237, 63%, 64%))
}

input:checked+ :hover {
  background: hsl(240, 100%, 90%);
}

input:focus+.slider {
  box-shadow: 0 0 1px hsl(237, 63%, 64%);
}

input:checked+.slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

.slider {
  border-radius: 34px;
}

.slider:hover {
  background: hsl(240, 100%, 90%);
}

.slider:before {
  border-radius: 50%;
}

.toggle-price p {
  display: inline-block;
  position: relative;
  top: 4px;
  color: hsl(234, 14%, 74%);
}

.card-title {
  font-family: Montserrat, sans-serif;
  font-weight: 700;
  font-size: 2rem;
  color: hsl(232, 13%, 33%);
}

.annual-price {
  display: none;
}
<div id="wrapper">

  <div class="pricing-header px-3 py-3 pt-md-5 pb-md-4 mx-auto text-center">

    <div class="toggle-price">
      <p class="annual">Annually</p>
      <label class="switch">
                      <input type="checkbox" id="myCheck" onClick="mouseToggleSwitch()" autofocus checked>
                      <span class="slider"></span>
                </label>
      <p class="month">Monthly</p>
    </div>
  </div>

  <div class="container">
    <div class="card-deck mb-3 text-center">

      <div class="card mb-4 shadow-sm">
        <div class="card-header">
          <h4 class="my-0">Basic</h4>
        </div>
        <div class="card-body">
          <h1 class="card-title pricing-card-title"><span class="monthly-price">&dollar;19.99</span>
            <span class="annual-price">&dollar;199.99</span></h1>
        </div>
      </div>
      <div class="card mb-4 shadow-sm highlight">
        <div class="card-header">
          <h4 class="my-0">Professional</h4>
        </div>
        <div class="card-body">
          <h1 class="card-title pricing-card-title"><span id="monthly-price">&dollar;24.99</span>
            <span class="annual-price">&dollar;249.99</span></h1>
        </div>
      </div>
      <div class="card mb-4 shadow-sm">
        <div class="card-header">
          <h4 class="my-0">Master</h4>
        </div>
        <div class="card-body">
          <h1 class="card-title pricing-card-title"><span class="monthly-price">&dollar;39.99</span>
            <span class="annual-price">&dollar;399.99</span></h1>
        </div>
      </div>

    </div>
  </div>

</div>

https://codepen.io/LizUK/pen/abOMQYx

Ответы [ 2 ]

0 голосов
/ 01 апреля 2020

function mouseToggleSwitch() {

  var checkBox = document.getElementById("myCheck");

  const clsName = checkBox.checked ? 'monthly-price' : 'annual-price';

  document.querySelectorAll('.monthly-price,.annual-price').forEach((x) => x.className == clsName ? x.style.display = "block" : x.style.display = "none");
}
.display-4 {
  font-size: 2rem;
  font-weight: 700;
  color: hsl(233, 13%, 49%);
  font-family: Montserrat, sans-serif;
}


/******* TOGGLE SWITCH *******/

.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
  margin: 0 20px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: linear-gradient(to right, hsl(236, 72%, 79%), hsl(237, 63%, 64%));
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked+.slider {
  background-image: linear-gradient(to right, hsl(236, 72%, 79%), hsl(237, 63%, 64%))
}

input:checked+ :hover {
  background: hsl(240, 100%, 90%);
}

input:focus+.slider {
  box-shadow: 0 0 1px hsl(237, 63%, 64%);
}

input:checked+.slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

.slider {
  border-radius: 34px;
}

.slider:hover {
  background: hsl(240, 100%, 90%);
}

.slider:before {
  border-radius: 50%;
}

.toggle-price p {
  display: inline-block;
  position: relative;
  top: 4px;
  color: hsl(234, 14%, 74%);
}

.card-title {
  font-family: Montserrat, sans-serif;
  font-weight: 700;
  font-size: 2rem;
  color: hsl(232, 13%, 33%);
}

.annual-price {
  display: none;
}
<div id="wrapper">

  <div class="pricing-header px-3 py-3 pt-md-5 pb-md-4 mx-auto text-center">

    <div class="toggle-price">
      <p class="annual">Annually</p>
      <label class="switch">
                          <input type="checkbox" id="myCheck" onClick="mouseToggleSwitch()" autofocus checked>
                          <span class="slider"></span>
                    </label>
      <p class="month">Monthly</p>
    </div>
  </div>

  <div class="container">
    <div class="card-deck mb-3 text-center">

      <div class="card mb-4 shadow-sm">
        <div class="card-header">
          <h4 class="my-0">Basic</h4>
        </div>
        <div class="card-body">
          <h1 class="card-title pricing-card-title"><span class="monthly-price">&dollar;19.99</span>
            <span class="annual-price">&dollar;199.99</span></h1>
        </div>
      </div>
      <div class="card mb-4 shadow-sm highlight">
        <div class="card-header">
          <h4 class="my-0">Professional</h4>
        </div>
        <div class="card-body">
          <h1 class="card-title pricing-card-title"><span class="monthly-price">&dollar;24.99</span>
            <span class="annual-price">&dollar;249.99</span></h1>
        </div>
      </div>
      <div class="card mb-4 shadow-sm">
        <div class="card-header">
          <h4 class="my-0">Master</h4>
        </div>
        <div class="card-body">
          <h1 class="card-title pricing-card-title"><span class="monthly-price">&dollar;39.99</span>
            <span class="annual-price">&dollar;399.99</span></h1>
        </div>
      </div>

    </div>
  </div>

</div>

Используя document.querySelectorAll, мы можем выбрать оба селектора месячная цена, годовая цена оттуда на основе имени класса, который мы можем назначить любому блоку или отобразить как ничего. Использование document.querySelectorAll ('span') не кажется идеальным, так как это может ввести в заблуждение, если до этого в документе были другие промежутки. Надеюсь, это поможет!

0 голосов
/ 01 апреля 2020

Вот так

Мне пришлось исправить идентификатор, который должен быть классом

ПРИМЕЧАНИЕ : я также инициализирую отображение на любой статус проверен на флажке при загрузке с сервера

Я также удалил встроенную функцию из флажка

function show(month) {
  document.querySelectorAll(".pricing-card-title").forEach(function(container) { 
    container.querySelector("span.monthly-price").style.display = month ? "block" : "none";
    container.querySelector("span.annual-price").style.display = month ? "none" : "block";
  })
}

window.addEventListener("load", function() { // on page load
  const chk = document.getElementById("myCheck")
  chk.addEventListener("click", function() {
    show(this.checked)
  })
  show(chk.checked); // initialise based on initial checked
})

function show(month) {
  document.querySelectorAll(".pricing-card-title").forEach(function(container) {
    container.querySelector("span.monthly-price").style.display = month ? "block" : "none";
    container.querySelector("span.annual-price").style.display = month ? "none" : "block";
  })
}

window.addEventListener("load", function() { // on page load
  const chk = document.getElementById("myCheck")
  chk.addEventListener("click", function() {
    show(this.checked)
  })
  show(chk.checked); // initialise based on initial checked
})
.display-4 {
  font-size: 2rem;
  font-weight: 700;
  color: hsl(233, 13%, 49%);
  font-family: Montserrat, sans-serif;
}


/******* TOGGLE SWITCH *******/

.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
  margin: 0 20px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: linear-gradient(to right, hsl(236, 72%, 79%), hsl(237, 63%, 64%));
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked+.slider {
  background-image: linear-gradient(to right, hsl(236, 72%, 79%), hsl(237, 63%, 64%))
}

input:checked+ :hover {
  background: hsl(240, 100%, 90%);
}

input:focus+.slider {
  box-shadow: 0 0 1px hsl(237, 63%, 64%);
}

input:checked+.slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

.slider {
  border-radius: 34px;
}

.slider:hover {
  background: hsl(240, 100%, 90%);
}

.slider:before {
  border-radius: 50%;
}

.toggle-price p {
  display: inline-block;
  position: relative;
  top: 4px;
  color: hsl(234, 14%, 74%);
}

.card-title {
  font-family: Montserrat, sans-serif;
  font-weight: 700;
  font-size: 2rem;
  color: hsl(232, 13%, 33%);
}
<div id="wrapper">

  <div class="pricing-header px-3 py-3 pt-md-5 pb-md-4 mx-auto text-center">

    <div class="toggle-price">
      <p class="annual">Annually</p>
      <label class="switch">
                      <input type="checkbox" id="myCheck" autofocus checked>
                      <span class="slider"></span>
                </label>
      <p class="month">Monthly</p>
    </div>
  </div>

  <div class="container">
    <div class="card-deck mb-3 text-center">

      <div class="card mb-4 shadow-sm">
        <div class="card-header">
          <h4 class="my-0">Basic</h4>
        </div>
        <div class="card-body">
          <h1 class="card-title pricing-card-title">
            <span class="monthly-price">&dollar;19.99</span>
            <span class="annual-price">&dollar;199.99</span></h1>
        </div>
      </div>
      <div class="card mb-4 shadow-sm highlight">
        <div class="card-header">
          <h4 class="my-0">Professional</h4>
        </div>
        <div class="card-body">
          <h1 class="card-title pricing-card-title">
            <span class="monthly-price">&dollar;24.99</span>
            <span class="annual-price">&dollar;249.99</span></h1>
        </div>
      </div>
      <div class="card mb-4 shadow-sm">
        <div class="card-header">
          <h4 class="my-0">Master</h4>
        </div>
        <div class="card-body">
          <h1 class="card-title pricing-card-title">
            <span class="monthly-price">&dollar;39.99</span>
            <span class="annual-price">&dollar;399.99</span></h1>
        </div>
      </div>

    </div>
  </div>

</div>

Короче, определяется месячной ценой - при условии, что годовой промежуток находится после месячного промежутка

function show(month) {
  document.querySelectorAll("span.monthly-price").forEach(function(span) { 
    span.style.display = month ? "block" : "none";
    span.nextElementSibling.style.display = month ? "none" : "block";
  })
}

// same "load" code as first snippet

function show(month) {
  document.querySelectorAll("span.monthly-price").forEach(function(span) { 
    span.style.display = month ? "block" : "none";
    span.nextElementSibling.style.display = month ? "none" : "block";
  })
}

window.addEventListener("load", function() { // on page load
  const chk = document.getElementById("myCheck")
  chk.addEventListener("click", function() {
    show(this.checked)
  })
  show(chk.checked); // initialise based on initial checked
})
.display-4 {
  font-size: 2rem;
  font-weight: 700;
  color: hsl(233, 13%, 49%);
  font-family: Montserrat, sans-serif;
}


/******* TOGGLE SWITCH *******/

.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
  margin: 0 20px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: linear-gradient(to right, hsl(236, 72%, 79%), hsl(237, 63%, 64%));
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked+.slider {
  background-image: linear-gradient(to right, hsl(236, 72%, 79%), hsl(237, 63%, 64%))
}

input:checked+ :hover {
  background: hsl(240, 100%, 90%);
}

input:focus+.slider {
  box-shadow: 0 0 1px hsl(237, 63%, 64%);
}

input:checked+.slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

.slider {
  border-radius: 34px;
}

.slider:hover {
  background: hsl(240, 100%, 90%);
}

.slider:before {
  border-radius: 50%;
}

.toggle-price p {
  display: inline-block;
  position: relative;
  top: 4px;
  color: hsl(234, 14%, 74%);
}

.card-title {
  font-family: Montserrat, sans-serif;
  font-weight: 700;
  font-size: 2rem;
  color: hsl(232, 13%, 33%);
}
<div id="wrapper">

  <div class="pricing-header px-3 py-3 pt-md-5 pb-md-4 mx-auto text-center">

    <div class="toggle-price">
      <p class="annual">Annually</p>
      <label class="switch">
                      <input type="checkbox" id="myCheck" autofocus checked>
                      <span class="slider"></span>
                </label>
      <p class="month">Monthly</p>
    </div>
  </div>

  <div class="container">
    <div class="card-deck mb-3 text-center">

      <div class="card mb-4 shadow-sm">
        <div class="card-header">
          <h4 class="my-0">Basic</h4>
        </div>
        <div class="card-body">
          <h1 class="card-title pricing-card-title">
            <span class="monthly-price">&dollar;19.99</span>
            <span class="annual-price">&dollar;199.99</span></h1>
        </div>
      </div>
      <div class="card mb-4 shadow-sm highlight">
        <div class="card-header">
          <h4 class="my-0">Professional</h4>
        </div>
        <div class="card-body">
          <h1 class="card-title pricing-card-title">
            <span class="monthly-price">&dollar;24.99</span>
            <span class="annual-price">&dollar;249.99</span></h1>
        </div>
      </div>
      <div class="card mb-4 shadow-sm">
        <div class="card-header">
          <h4 class="my-0">Master</h4>
        </div>
        <div class="card-body">
          <h1 class="card-title pricing-card-title">
            <span class="monthly-price">&dollar;39.99</span>
            <span class="annual-price">&dollar;399.99</span></h1>
        </div>
      </div>

    </div>
  </div>

</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...