Переключить статус галочки в галочке галочки с гиперссылкой - PullRequest
7 голосов
/ 13 мая 2019

Мы с коллегой работали над сайтом, на котором есть страница часто задаваемых вопросов. После каждого вопроса есть кнопка спойлера «Ответ» (Antwoord). При нажатии на кнопку отображается ответ под текущим вопросом и над следующим вопросом. Повторное нажатие на кнопку скрывает ответ. Это позволяет легко прокручивать список всех вопросов и найти интересующий вас вопрос.

Теперь проблема, с которой я сталкиваюсь, заключается в том, что я хочу дать ссылку, например, на ответ на вопрос 5 из ответа на вопрос 1.

Я мог бы дать <div>, содержащему вопрос 5, свойство id= для ссылки на него, но в идеале я хочу показать ответ сразу, сделав гиперссылку «щелкнуть» по кнопке «Ответить».

Оказывается, мне нужно изменить хак с флажками, чтобы это работало должным образом, но я столкнулся с проблемой, что у меня не может быть и гиперссылки, и метки на одном фрагменте текста.

Просто чтобы прояснить: Я ищу решение, использующее только HTML / CSS.


Мой оригинальный код с помощью кнопки спойлера

.spoilerbutton {
  display: block;
  border: none;
  padding: 0px 0px;
  margin: 10px 0px;
  font-size: 150%;
  font-weight: bold;
  color: #000000;
  background-color: transparent;
  outline: 0;
}

.spoiler {
  overflow: hidden;
}

.spoiler>div {
  -webkit-transition: all 0s ease;
  -moz-transition: margin 0s ease;
  -o-transition: all 0s ease;
  transition: margin 0s ease;
}

.spoilerbutton[value="Antwoord"]+.spoiler>div {
  margin-top: -500%;
}

.spoilerbutton[value="Hide Antwoord"]+.spoiler {
  padding: 5px;
}
<strong>1. Question 1?</strong> <input class="spoilerbutton" onclick="this.value=this.value=='Antwoord'?'Verberg':'Antwoord';" type="button" value="Antwoord" />
<div class="spoiler">
  <div>
    <ul>
      <li>possible answer 1.</li>
      <li>possible answer 2.</li>
      <li>possible answer 3.</li>
    </ul>
  </div>
</div>

Попытка реализовать решения из: Можно ли получить эффект щелчка в CSS?

Я получаю следующее, что не работает:

#btnControll1 {
    display: none;
}

.spoilerbutton {
  display: block;
  border: none;
  padding: 0px 0px;
  margin: 10px 0px;
  font-size: 150%;
  font-weight: bold;
  color: #000000;
  background-color: transparent;
  outline: 0;
}

.spoiler {
  overflow: hidden;
}

.spoiler>div {
  -webkit-transition: all 0s ease;
  -moz-transition: margin 0s ease;
  -o-transition: all 0s ease;
  transition: margin 0s ease;
}

#btnControl1:checked + label {
margin-top; -500%
}
<strong>1. Question 1?</strong> <input type"chekbox" id="btnControl1" />
<label class="spoilerbutton" for="btnControl1">Antwoord</label>
<div class="spoiler">
  <div>
    <ul>
      <li>possible answer 1.</li>
      <li>possible answer 2.</li>
      <li>possible answer 3.</li>
    </ul>
  </div>
</div>

Использование комбинаций <label> и <a href> (также не работает)

.spoilerbutton {
display: none;
}
.spoiler {
overflow: hidden;
height:2em;
}
.spoiler>div {
-webkit-transition: all 0s ease;
-moz-transition: margin 0s ease;
-o-transition: all 0s ease;
transition: margin 0s ease;
}
.spoilerbutton+.spoiler>div {
margin-top: -500%;
}
.spoilerbutton+.spoiler>label:before {
content: 'Antwoord';
font-size: 150%;
font-weight: bold;
color: #000000;
}
.spoilerbutton:checked+.spoiler>label:before {
content: 'Verberg';
}
.spoilerbutton:checked+.spoiler {
height:auto;
}
.spoilerbutton:checked+.spoiler>div {
margin-top: 0;
}
<strong>1. Question 1?</strong> <input type="checkbox" id="question1" value="checked" class="spoilerbutton">
<div class="spoiler">
<label for="question1"></label>
<div>
<ul>
<li><a href="#question5"><label for="#answer5">Open 5. link first</label></a></li>
<li><label for="question5"><a href="#answer5">Open 5. label first</a></label></li>
<li><a href="#answer5">Open 5. link only</a></li>
</ul>
</div>
</div>
<strong>2. Question 2?</strong> <input type="checkbox" id="question2" value="checked" class="spoilerbutton">
<div class="spoiler">
<label for="question2"></label>
<div>
<ul>
<li>possible answer 1.</li>
<li>possible answer 2.</li>
<li>possible answer 3.</li>
</ul>
</div>
</div>
<strong>2. Question 3?</strong> <input type="checkbox" id="question3" value="checked" class="spoilerbutton">
<div class="spoiler">
<label for="question3"></label>
<div>
<ul>
<li>possible answer 1.</li>
<li>possible answer 2.</li>
<li>possible answer 3.</li>
</ul>
</div>
</div>
<strong>2. Question 4?</strong> <input type="checkbox" id="question4" value="checked" class="spoilerbutton">
<div class="spoiler">
<label for="question4"></label>
<div>
<ul>
<li>possible answer 1.</li>
<li>possible answer 2.</li>
<li>possible answer 3.</li>
</ul>
</div>
</div>
<br>
<br>
<br>
<br><br>
<br><br>
<br><br>
<br><br>
<br><br>
<br><br>
<br><br>
<br><br>
<br><br>
<br><br>
<br>
<strong>2. Question 5?</strong> <input type="checkbox" id="question5" value="checked" class="spoilerbutton">
<div class="spoiler" id="answer5">
<label for="question5"></label>
<div>
<ul>
<li>possible answer 1.</li>
<li>possible answer 2.</li>
<li>possible answer 3.</li>
</ul>
</div>
</div>

Также связано Как установить флажок при нажатии на ссылку?

Там есть несколько отличных предложений, но я не могу адаптировать ответ от Tushar к моей ситуации.

Ответы [ 5 ]

8 голосов
/ 15 мая 2019

Вариант 1 - Использование JavaScript

Перенаправление работает только в том случае, если элемент видим, но не установлен на display: none. В приведенном выше фрагменте кода как флажок, так и список ответов установлены в display: none в качестве исходного состояния.

Шаг 1: Добавьте id к каждому элементу <strong id="question">.

<strong id="question1">1. Question 1?</strong> 

Шаг 2: Мы не можем поставить / снять флажок с помощью CSS, мы должны использовать JavaScript / jQuery для достижения этой функциональности. Поэтому я добавил основы в скрипт флажок , когда пользователь нажимает на ссылку.

<li><a href="#question5" onClick="var str = this.attributes['href'].value + 'Checkbox'; document.getElementById(str.replace('#', '')).checked = true;">Open 5. link first</a></li>

.spoilerbutton {
display: none;
}
.spoiler {
overflow: hidden;
height:2em;
}
.spoiler>div {
-webkit-transition: all 0s ease;
-moz-transition: margin 0s ease;
-o-transition: all 0s ease;
transition: margin 0s ease;
}
.spoilerbutton+.spoiler>div {
margin-top: -500%;
}
.spoilerbutton+.spoiler label:before {
content: 'Antwoord';
font-size: 150%;
font-weight: bold;
color: #000000;
}
.spoilerbutton:checked+.spoiler label:before {
content: 'Verberg';
}
.spoilerbutton:checked+.spoiler {
height:auto;
}
.spoilerbutton:checked+.spoiler>div {
margin-top: 0;
}
<strong id="question1">1. Question 1?</strong> 
<input type="checkbox" id="question1Checkbox" value="checked" class="spoilerbutton">
  <div class="spoiler">
    <label for="question1Checkbox"></label>
    <div>
      <ul>
        <li><a href="#question5" onClick="var str = this.attributes['href'].value + 'Checkbox'; document.getElementById(str.replace('#', '')).checked = true;">Open 5. link first</a></li>
      </ul>
    </div>
</div>
<strong id="question2">2. Question 2?</strong> 
<input type="checkbox" id="question2Checkbox" value="checked" class="spoilerbutton">
<div class="spoiler">
  <label for="question2Checkbox"></label>
  <div>
    <ul>
      <li>possible answer 1.</li>
      <li>possible answer 2.</li>
      <li>possible answer 3.</li>
    </ul>
  </div>
</div>
<strong id="question3">2. Question 3?</strong> 
<input type="checkbox" id="question3Checkbox" value="checked" class="spoilerbutton">
<div class="spoiler">
  <label for="question3Checkbox"></label>
  <div>
    <ul>
      <li>possible answer 1.</li>
      <li>possible answer 2.</li>
      <li>possible answer 3.</li>
    </ul>
  </div>
</div>
<strong id="question4">2. Question 4?</strong> 
<input type="checkbox" id="question4Checkbox" value="checked" class="spoilerbutton">
<div class="spoiler">
  <label for="question4Checkbox"></label>
  <div>
    <ul>
      <li>possible answer 1.</li>
      <li>possible answer 2.</li>
      <li>possible answer 3.</li>
    </ul>
  </div>
</div>
<br>
<br>
<br>
<br><br>
<br><br>
<br><br>
<br><br>
<br><br>
<br><br>
<br><br>
<br><br>
<br><br>
<br><br>
<br>
<strong id="question5">2. Question 5?</strong> 
<input type="checkbox" id="question5Checkbox" value="checked" class="spoilerbutton">
<div class="spoiler" id="answer5">
  <label for="question5Checkbox"></label>
  <div>
    <ul>
      <li>possible answer 1.</li>
      <li>possible answer 2.</li>
      <li>possible answer 3.</li>
    </ul>
  </div>
</div>

Вариант 2 - Использование CSS

С помощью селектора CSS :target и небольшого обновления структуры мы можем достичь функциональности с помощью CSS.

.spoilerbutton {
display: none;
}
.spoiler {
overflow: hidden;
height:2em;
}
.spoiler>div {
-webkit-transition: all 0s ease;
-moz-transition: margin 0s ease;
-o-transition: all 0s ease;
transition: margin 0s ease;
}
.spoilerbutton+.spoiler .listOfAnswer {
margin-top: -500%;
}
.spoilerbutton+.spoiler .labelWrap {
  display: inline-block;
  position: relative;
}
.spoilerbutton+.spoiler .labelWrap label:before {
content: 'Antwoord';
font-size: 150%;
font-weight: bold;
color: #000000;
}
.spoilerbutton:checked+.spoiler .labelWrap label:before {
content: 'Verberg';
}
.spoilerbutton:checked+.spoiler {
height:auto;
}
.spoilerbutton:checked+.spoiler .listOfAnswer {
margin-top: 0;
}

:target + .spoilerbutton + .spoiler {
height:auto;
}
:target + .spoilerbutton + .spoiler .labelWrap label:before {
content: 'Verberg';
}
:target + .spoilerbutton + .spoiler .labelWrap .resetTarget {
cursor: default;
display: block;
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
}
:target + .spoilerbutton + .spoiler .listOfAnswer {
margin-top: 0;
}
.resetTarget {
  display: none;
}
<strong class="qTitle" id="question1">1. Question 1?</strong> 
<input type="checkbox" id="question1Checkbox" value="checked" class="spoilerbutton">
  <div class="spoiler">
    <div class="labelWrap">
      <label for="question1Checkbox"></label>
      <a class="resetTarget" href="#question1Checkbox"></a>
    </div>
    <div class="listOfAnswer">
      <ul>
        <li><a href="#question5">Open 5. link first</a></li>
      </ul>
    </div>
</div>
<strong class="qTitle" id="question2">2. Question 2?</strong> 
<input type="checkbox" id="question2Checkbox" value="checked" class="spoilerbutton">
<div class="spoiler">
  <div class="labelWrap">
    <label for="question2Checkbox"></label>
    <a class="resetTarget" href="#question2Checkbox"></a>
  </div>
  <div class="listOfAnswer">
    <ul>
      <li>possible answer 1.</li>
      <li>possible answer 2.</li>
      <li>possible answer 3.</li>
    </ul>
  </div>
</div>
<strong class="qTitle" id="question3">2. Question 3?</strong> 
<input type="checkbox" id="question3Checkbox" value="checked" class="spoilerbutton">
<div class="spoiler">
  <div class="labelWrap">
    <label for="question3Checkbox"></label>
    <a class="resetTarget" href="#question3Checkbox"></a>
  </div>
  <div class="listOfAnswer">
    <ul>
      <li>possible answer 1.</li>
      <li>possible answer 2.</li>
      <li>possible answer 3.</li>
    </ul>
  </div>
</div>
<strong class="qTitle" id="question4">2. Question 4?</strong> 
<input type="checkbox" id="question4Checkbox" value="checked" class="spoilerbutton">
<div class="spoiler">
  <div class="labelWrap">
    <label for="question4Checkbox"></label>
    <a class="resetTarget" href="#question4Checkbox"></a>
  </div>
  <div class="listOfAnswer">
    <ul>
      <li>possible answer 1.</li>
      <li>possible answer 2.</li>
      <li>possible answer 3.</li>
    </ul>
  </div>
</div>
<br>
<br>
<br>
<br><br>
<br><br>
<br><br>
<br><br>
<br><br>
<br><br>
<br><br>
<br><br>
<br><br>
<br><br>
<br>
<strong class="qTitle" id="question5">2. Question 5?</strong> 
<input type="checkbox" id="question5Checkbox" value="checked" class="spoilerbutton">
<div class="spoiler" id="answer5">
  <div class="labelWrap">
    <label for="question5Checkbox">
      <a class="resetTarget" href="#question5Checkbox"></a>
    </label>    
  </div>
  <div class="listOfAnswer">
    <ul>
      <li>possible answer 1.</li>
      <li>possible answer 2.</li>
      <li>possible answer 3.</li>
    </ul>
  </div>
</div>
3 голосов
/ 15 мая 2019

Краткий ответ

В общем, да, это возможно сделать, но у него есть огромные ограничения из-за ограничений CSS ( Cascading Style Sheets), так что на самом деле ответ нет .


Длинный ответ

Проблема, с которой мы сталкиваемся, заключается в том, что вы не сможете реализовать решение динамически без каких-либо JavaScript.Вы можете видеть, что в возможном ответе вы связались.В чистом CSS это возможно только для элементов, указанных в файле.Как CSS может узнать, какой checkbox проверить (при условии использования хака checkbox) или какой ответ расширить, если вы нажмете на ссылку?Ответ прост: Он не может .

Так что единственный способ сделать это без JavaScript - это сделать это не динамически.Проблема в том, что вы не можете нацеливаться на родительские элементы ( Каскадные Таблицы стилей), поэтому нет даже чистого способа CSS даже открыть другой элемент, если, например, гиперссылка находится в :focusи вы также не можете установить / снять флажки с помощью CSS.

Это приводит нас к JavaScript как единственно возможному решению с вашей структурой кода.

.spoilerbutton {
  position: absolute;
  margin-top: 9px 0 0 -5px;
  height: 35px;
  width: 102px;
  opacity: 0;
}

.spoilerbutton:checked {
  width: 86px;
}

.spoilerbutton~.text::after {
  content: "Antwoord";
}

.spoilerbutton:checked~.text::after {
  content: "Verberg";
}

.spoilerbutton~.spoiler {
  display: none;
}

.spoilerbutton:checked~.spoiler {
  padding: 5px;
  display: block;
}
<div>
  <strong>1. Question 1?</strong>
  <p class="text"></p>
  <input class="spoilerbutton" type="checkbox" />

  <h2 class="text"></h2>

  <div class="spoiler">
    <div>
      <ul>
        <li><a onclick="document.querySelector(this.attributes['href'].value + ' .spoilerbutton').checked = true;" href="#answer3">Open answer 3</a></li>
        <li>possible answer 2.</li>
        <li>possible answer 3.</li>
      </ul>
    </div>
  </div>
</div>

<div>
  <strong>1. Question 2?</strong>
  <p class="text"></p>
  <input class="spoilerbutton" type="checkbox" />

  <h2 class="text"></h2>

  <div class="spoiler">
    <div>
      <ul>
        <li>possible answer 1.</li>
        <li>possible answer 2.</li>
        <li>possible answer 3.</li>
      </ul>
    </div>
  </div>
</div>

<div style="margin-top: 500px" id="answer3">
  <strong>1. Question 3?</strong>
  <p class="text"></p>
  <input class="spoilerbutton" type="checkbox" />

  <h2 class="text"></h2>

  <div class="spoiler">
    <div>
      <ul>
        <li>possible answer 1.</li>
        <li>possible answer 2.</li>
        <li>possible answer 3.</li>
      </ul>
    </div>
  </div>
</div>

Достаточно одной строки кода:

document.querySelector(this.attributes['href'].value + ' .spoilerbutton').checked = true;

Редактировать

На самом деле я забыл о :target псевдокласс.Но Хасан Сиддики уже завершил свой ответ этим.Однако вам придется реструктурировать свой код, и если вы хотите использовать подход JavaScript (который я настоятельно рекомендую), я предпочитаю свою строку кода.

1 голос
/ 18 мая 2019

Следующая демонстрация - чистый HTML / CSS, а не немного JavaScript.Это включает в себя атрибуты события, которые многие игнорируют и не осознают, что они являются JavaScript.Вот два примера:

<button onclick = "jsFunction (this); вернуть false" >X</button>

<a href="#/" onclick ="this.value = this.value == 'Antwoord'? 'Verberg': 'Antwoord';" >X</a>

Каждый вопрос и ответ - это скрытый флажок, свернутый набор полей, содержащийвидимая легенда и метка, а также список определений как скрытый контент.visibility: collapse/visible был использован для этой части.

Мы используем :target, чтобы открыть целевой набор полей при прыжке на него.Все взаимодействие с пользователем и анимация работают (даже прокрутка с использованием scroll-behavior: smooth) исключительно за счет классно-ориентированного CSS и стратегического HTML-макета.Никаких компромиссов не было сделано с использованием тонны <br> или с использованием любого JavaScript.Единственный #id, используемый в CSS, был несущественным набором правил, так что пока вы придерживаетесь шаблона макета и расширение назначений классов должно быть безболезненным.

Обновление
принесло HassanSiddiquiк моему намерению крайнего случая см. комментарий ниже.Я говорю «крайний случай», потому что я не вижу пользователей, которые так часто задают вопросы и ответы, что им нужно вернуться и использовать эту конкретную ссылку.Тем не менее, для полноты картины я обновил его следующим текстом:

  1. label.tgr для вопроса № 5 изначально display:none.

  2. Вместо него стоит a.tgr, который ставит флажок в вопросе № 5, input#act5.

  3. Теперь сделайте резервную копию по ссылке в вопросе № 1 и давайте вспомним, что там происходит:при нажатии на эту ссылку fieldset#t5c2 сейчас и навсегда :target, что затрудняет закрытие, поскольку input#act5 не проверено.

  4. Итак, #t5c2 была открыта по ссылке, и этосейчас :target.Чтобы удалить это состояние из #t5c2 a.tgr, нажмите input#act5:target.

  5. Таким образом, a.tgr будет заменено на label.tgr и #t5c2 будет закрыто,Я не буду вдаваться в подробности, я запутываю себя, поэтому просто просмотрите CSS.

Просмотрите демонстрацию в режиме полной страницы, iframe фрагмента в начальнойкомпактный режим ужасно диспропорционален.

html {
  scroll-behavior: smooth;
}

.main {
  height: 300vh;
  padding: 2vh 2vw 30vh;
}

.set {
  overflow: hidden;
  visibility: collapse;
  margin: 2vh 0;
}

.cat {
  max-height: 0;
  font-size: 0;
  opacity: 0;
}

:target .cat,
.act:checked+.set .cat {
  max-height: 100vh;
  font-size: 1rem;
  opacity: 1.0;
  transition: opacity 1s, max-height 0.7s;
}

:target,
.act:checked+.set {
  max-height: 100vh;
  visibility: visible;
  transition: 0.7s
}

.que,
.tgr {
  visibility: visible;
  max-height: 50vh;
  color: #000;
  font-size: 1rem;
  text-decoration: none;
}

.tgr {
  cursor: pointer;
}

.que::before {
  content: attr(data-idx)'. ';
}

.lnx::after {
  content: ' 'attr(title);
}


/* Question 5 Switch Triggers */

#act1:checked~.set .top {
  outline: 3px solid cyan
}

#act5:target+#t5c2 {
  visibility: collapse;
}

#act5:checked+#t5c2 {
  visibility: visible;
}

#t5c2 label.tgr {
  display: none;
}

#act5:target+#t5c2 label {
  display: inline-block;
}

#act5:target+#t5c2 a {
  display: none;
}

#act1:not(:checked)~#act5:not(:checked)+#t5c2:not(:target) a {
  display: none;
}

#act1:not(:checked)~#act5:not(:checked)+#t5c2:not(:target) label {
  display: inline-block;
}
<form class='main'>

  <input id='act1' class="act" type="checkbox" hidden>
  <fieldset class='set'>
    <legend class='que' data-idx='1'>Question</legend>
    <label class='tgr' for='act1'>Answers</label>
    <dl class='cat'>
      <dt>Category 1A</dt>
      <dd>Topic 1A1</dd>
      <dd>Topic 1A2</dd>
      <dt>Category 1B</dt>
      <dd>Topic 1B1
        <a href='#t5c2' class='lnx' title='Topic 5C2'>Also see</a>
      </dd>
      <dd>Topic 1B2</dd>
    </dl>
  </fieldset>

  <input id='act2' class="act" type="checkbox" hidden>
  <fieldset class='set'>
    <legend class='que' data-idx='2'>Question</legend>
    <label class='tgr' for='act2'>Answers</label>
    <dl class='cat'>
      <dt>Category 2A</dt>
      <dd>Topic 2A1</dd>
      <dd>Topic 2A2</dd>
      <dt>Category 2B</dt>
      <dd>Topic 2B1</dd>
    </dl>
  </fieldset>

  <input id='act3' class="act" type="checkbox" hidden>
  <fieldset class='set'>
    <legend class='que' data-idx='3'>Question</legend>
    <label class='tgr' for='act3'>Answers</label>
    <dl class='cat'>
      <dt>Category 3A</dt>
      <dd>Topic 3A1</dd>
      <dt>Category 3B</dt>
      <dd>Topic 3B1</dd>
      <dd>Topic 3B2</dd>
      <dd>Topic 3B3</dd>
    </dl>
  </fieldset>

  <input id='act4' class="act" type="checkbox" hidden>
  <fieldset class='set'>
    <legend class='que' data-idx='4'>Question</legend>
    <label class='tgr' for='act4'>Answers</label>
    <dl class='cat'>
      <dt>Category 4A</dt>
      <dd>Topic 4A1</dd>
      <dd>Topic 4A2</dd>
      <dd>Topic 4A3</dd>
    </dl>
  </fieldset>

  <input id='act5' class="act" type="checkbox" hidden>
  <fieldset id='t5c2' class='set'>
    <legend class='que' data-idx='5'>Question</legend>
    <label class='tgr' for='act5'>Answers</label>
    <a href='#act5' class='tgr'>Answers</a>
    <dl class='cat'>
      <dt>Category 5A</dt>
      <dd>Topic 5A1</dd>
      <dd>Topic 5A2</dd>
      <dt>Category 5B</dt>
      <dd>Topic 5B1</dd>
      <dd>Topic 5B2</dd>
      <dt>Category 5C</dt>
      <dd>Topic 5C1</dd>
      <dd class='top'>Topic 5C2</dd>
    </dl>
  </fieldset>

</form>
0 голосов
/ 18 мая 2019

Другие ответы иллюстрируют недостатки в решении этого без JavaScript.

С точки зрения семантики, я рекомендую использовать элемент details .

Чтобы связать один вопрос с другим и одновременно открыть этот ответ, используйте небольшой скрипт для программного обновления атрибута [open] в элементах details.

const section = document.getElementById('section');

section.addEventListener('click', (e) => {
  const target = e.target;
  const isLink = target.classList.contains('link');

  if (!isLink) {
    return;
  }

  const href = target.getAttribute('href');
  const question = target.closest('section').querySelector(href);

  question.setAttribute('open', true);
});
body {
  height: 2000px;
}

summary {
  cursor: pointer;
}
<section id="section">
  <details id="q1">
    <summary>Question 1</summary>
    <ul>
      <li>possible answer 1.</li>
      <li>possible answer 2.</li>
      <li>see the answer to <a class="link" href="#q4">question 4</a></li>
    </ul>
  </details>
  <details id="q2">
    <summary>Question 2</summary>
    <ul>
      <li>possible answer 1.</li>
      <li>possible answer 2.</li>
      <li>possible answer 3.</li>
    </ul>
  </details>
  <details id="q3">
    <summary>Question 3</summary>
    <ul>
      <li>possible answer 1.</li>
      <li>possible answer 2.</li>
      <li>possible answer 3.</li>
    </ul>
  </details>
  <details id="q4">
    <summary>Question 4</summary>
    <ul>
      <li>possible answer 1.</li>
      <li>possible answer 2.</li>
      <li>possible answer 3.</li>
    </ul>
  </details>
</section>
0 голосов
/ 16 мая 2019

Я немного упростил код и создал полуработающую опцию чистого CSS.Я не смог заставить его работать точно так, как вы ищете, но я полагаю, что кто-то может все еще найти его полезным.

По сути, я использовал селектор :focus psuedo для отображения ответов при нажатии кнопок.

Я также пытался использовать селектор :active для отображения ответа из другого ответа.Это не очень хорошо работает, потому что селектор :active исчезает, как только элемент не активен.

Тем не менее, это возможное решение для простого отображения ответов при нажатии кнопки.

/* some quick styling */

.question {
  font-weight: bold;
  margin: 10px 0;
}

.answer {
  display: none;
  font-size: 14px;
  margin: 10px 0;
}

.show-answer {
  background: #cceedd;
}

.show-answer:focus {
  background: #cdcdcd;
}

a.answer-link {
  color: black;
  text-decoration: none;
}

a.answer-link span {
  color: blue;
  text-decoration: underline;
}

/* displaying the answers */

.show-answer:focus + .answer {
  display: block;
}

/* linking to an answer */

.answer-link--2:active ~ .answer--2 {
  display: block;
}
<div class="question">Question 1?</div>
<button class="show-answer show-answer--1">Show Answer</button>
<a class="answer answer--1 answer-link answer-link--2" href="#">This is the answer to Question 1. <span>Clicking and holding this text will open Question 2 answer, until you let go!.</span>.</a>
<hr/>
<div class="question">Question 2?</div>
<button class="show-answer show-answer--2">Show Answer</button>
<div class="answer answer--2">This is the answer to Question 2.</div>
<hr/>
<div class="question">Question 3?</div>
<button class="show-answer show-answer--3">Show Answer</button>
<div class="answer answer--3">This is the answer to Question 3.</div>
<hr/>
<div class="question">Question 4?</div>
<button class="show-answer show-answer--4">Show Answer</button>
<div class="answer answer--4">This is the answer to Question 4.</div>
<hr/>
<div class="question">Question 5?</div>
<button class="show-answer show-answer--5">Show Answer</button>
<div class="answer answer--5">This is the answer to Question 5.</div>
...