Создайте кнопку CSS, чтобы при нажатии отображать количество текста x и измените размер тега div - PullRequest
2 голосов
/ 29 февраля 2020

У меня есть проект, который я делаю для друга. Я хочу отобразить некоторый текст, и при нажатии кнопки «узнать больше» появится оставшаяся часть текста. Я разделил видимый и невидимый текст на отдельные теги

и присвоил им имя класса - их 3.

  <div class="column">
    <h2> BCI </h2>

    <p class="visible_text">
        The Better Cotton
        Initiative (BCI) is a global
        non-profit organisation
        cemented around being
        the largest cotton sustainability
        programme in the
        world.
    </p>

    <p class="non_visible_text">
        The Better Cotton Initiative (BCI) is a global non-profit organisation
        cemented around being the largest cotton sustainability
        programme in the world. Striving towards better global cotton
        production, in terms of bettering the lives of those who produce
        it, better for the environment it grows in and better for the
        sector’s future.
        Thanks to the help of several partners, the BCI provides training
        on more sustainable farming practices to more than two million
        cotton farmers in 21 countries. In the 2017-18 cotton season,
        licensed BCI Farmers produced more than five million metric
        tonnes of ‘Better Cotton’ – that accounts for around 19% of
        global cotton production!
    </p>


    <button class="learnBtn">
        <img src="images/LearnMore.png" alt="Learn More Button">
    </button>
</div>

Поэтому, когда кнопка нажата, я хочу, чтобы текст класс «non_visible_text» для отображения под «visible_text».

Есть идеи?

Ответы [ 3 ]

1 голос
/ 29 февраля 2020

Если вы ищете опцию css, вам нужно ввести (type = checkbox) перед элементом, который вы хотите обновить стиль, независимо от того, отмечен он или нет, и добавить метку, связанную с ним через атрибут for, чтобы он мог стоять где угодно:

возможный пример:

#more {/* hide this one */
  position: absolute;
  right: 100vw;
}

.non_visible_text {
  display: none; 
}

label[for="more"] {/* use a label linked to the checkbox, style it like a button if you wish */
  -moz-appearance: button;
  appearance: button;
}

label[for="more"]:after {
  content: ' more.'/* update text */
}

#more:checked~.non_visible_text {
  display: block;/* show hidden tag */
}

#more:checked~label[for="more"]:after {
  content: ' less.'/* update text */
}
<div class="column">
 <h2>HTML Ipsum Presents</h2>

  <p class="visible_text">Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>
  <input type="checkbox" id="more" />
  <p class="non_visible_text">Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p>


  <label class="learnBtn" for="more">
        see 
    </label>
</div>

Вот также метод javascript для текстового содержимого вашей кнопки:

var myButton    = document.querySelector(".learnBtn");
var text2toggle = document.querySelector(".non_visible_text");

myButton.addEventListener("click", function() {
  if ((myButton.textContent === "see more")) {
    text2toggle.style.display = "block";
    myButton.textContent = "see less";
  } else {
    text2toggle.style.display = "none";
    myButton.textContent = "see more";
  }
});
.non_visible_text {
  display: none
}
<div class="column">
  <h2>HTML Ipsum Presents</h2>

  <p class="visible_text">Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est.
    Mauris placerat eleifend leo.</p>
  <p class="non_visible_text">Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est.
    Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus
    lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor,
    facilisis luctus, metus</p>


  <button type="text" class="learnBtn">see more</button>
</div>
0 голосов
/ 29 февраля 2020

Это заняло у меня много времени, вот код. (Изменен ваш код для работы с кнопкой переключения)

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.visible {
	visibility: hidden;
}

.less::after {
	content: ' Less'
}

.more::after {
	content: ' More'
}
</style>
</head>
<body>
<h2> BCI </h2>
<p class="visible_text">
        The Better Cotton
        Initiative (BCI) is a global
        non-profit organisation
        cemented around being
        the largest cotton sustainability
        programme in the
        world.
    </p>

<button onclick="element.classList.toggle('visible'); element2.classList.toggle('more');" id='toggleBTN' class='less'>Learn</button>

<p id="toggleP" style='display:block'>
        The Better Cotton Initiative (BCI) is a global non-profit organisation
        cemented around being the largest cotton sustainability
        programme in the world. Striving towards better global cotton
        production, in terms of bettering the lives of those who produce
        it, better for the environment it grows in and better for the
        sector’s future.
        Thanks to the help of several partners, the BCI provides training
        on more sustainable farming practices to more than two million
        cotton farmers in 21 countries. In the 2017-18 cotton season,
        licensed BCI Farmers produced more than five million metric
        tonnes of ‘Better Cotton’ – that accounts for around 19% of
        global cotton production!
</p>

<script>
   var element = document.getElementById("toggleP");
   var element2 = document.getElementById('toggleBTN');
</script>

</body>
</html>
0 голосов
/ 29 февраля 2020

Одна из техник, которую вы можете использовать, это использование класса :target CSS - я использую это для отображения материала без необходимости использовать Javascript.

:target правила будут применяться всякий раз, когда id элемента соответствует фрагменту URL, поэтому все, что находится после #. Затем измените вашу кнопку на ссылку #id:

.non_visible_text {
  display: none;
}

.non_visible_text:target {
  display: inline;
}

.non_visible_text:target + .visible_text {
  display: none;
}
    <p id="read-more" class="non_visible_text">
      longer text
    </p>
    
    <p class="visible_text">
      short text
    </p>


    <a href="#read-more" class="learnBtn">
        <img src="images/LearnMore.png" alt="Learn More Button">
    </a>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...