Мы с коллегой работали над веб-сайтом, на котором есть страница часто задаваемых вопросов. После каждого вопроса есть спойлерная кнопка "Ответить"(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>Попытка реализовать решения из:Могу ли я иметь эффект onclick в 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>Также связанныеКак переключить флажок при нажатии на ссылку?
Там есть несколько замечательных предложений, но я не могу адаптировать ответ отТушар к моей ситуации.
@Aaron3219 Aaron3219, ну, тогда я думаю, что это то, что мы сейчас используем, и это работает. Yay для того, чтобы сделать что-то на языке, о котором вы очень мало знаете!
Что насчет моего второго вопроса? Я правильно вас понял?
Если я нажму «Перейти к ответу 5» (в последнем фрагменте моего вопроса), я хочу, чтобы фокус экрана был на вопросе 5, а ответы были видны сразу.
@Luuklag я обновил свой ответ, и вы можете найти рабочий пример для обоих вариантов CSS и jQuery. Спасибо






Option 1 - Using 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>Option 2 - Using 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>«Мы не можем установить/снять флажок с помощью CSS». Да, вы можете, это хорошо известная интерактивная техника, основанная только на CSS, которую часто называют взломом флажка.
В общем, да, это возможно сделать, но у него есть огромные ограничения из-за ограничений CSS (листы Каскадный стиль), поэтому на самом деле ответ будет нет.
Проблема, с которой мы сталкиваемся, заключается в том, что вы не сможете реализовать решение динамически без каких-либо 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 (который я настоятельно рекомендую), я предпочитаю свою строку кода.
Хорошее объяснение и анализ. Мне также нравится подход с использованием querySelector вместо getElementById, как это сделал @Хасан Сиддики.
Я немного упростил код и создал полурабочий вариант на чистом CSS. Мне не удалось заставить его работать именно так, как вы ищете, но я полагаю, что кто-то все еще может найти его полезным.
По сути, я использовал псевдоселектор :focus для отображения ответов при нажатии кнопок.
Я также попытался использовать селектор :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>Другие ответы продемонстрировали недостатки решения этой проблемы без JavaScript.
С точки зрения семантики я рекомендую использовать элемент подробности.
Чтобы связать один вопрос с другим и одновременно показать этот ответ, используйте небольшой скрипт для программного обновления атрибута [open] в элементах сведений.
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>Следующая демонстрация представляет собой чистый HTML/CSS, а не JavaScript. Это включает в себя атрибуты события, которые многие упускают из виду и не понимают, что они являются JavaScript. Вот два примера:
<buttononclick = "jsFunction(this); return 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 довел до моего намерения крайний случай, см. комментарий ниже. Я говорю крайний случай, потому что я не вижу, чтобы пользователь останавливался на часто задаваемых вопросах настолько, чтобы у него возникала необходимость вернуться и использовать эту конкретную ссылку. Тем не менее, для полноты картины я обновил его следующим:
label.tgr для вопроса № 5 изначально display:none.
На его месте находится a.tgr, который нацелен на флажок Вопроса № 5, input#act5.
Теперь сделайте резервную копию ссылки в вопросе № 1 и давайте вспомним, что там происходит: при нажатии на эту ссылку fieldset#t5c2 происходит сейчас и навсегда :target, что затрудняет ее закрытие, поскольку input#act5 не отмечен.
Итак #t5c2 открылась по ссылке и теперь :target. Чтобы удалить это состояние из #t5c2a.tgr, нажмите, чтобы сделать input#act5:target.
Итак, в этот момент 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>Поскольку я считаю, что это самый простой код в HTML, я присудил награду. Это очень важно, так как вопросов много.
Действительно, простота и функциональность являются ключом к поддержанию стабильного кода. Удачного кодирования!
@ zer00ne - он работает только в первый раз, когда вы нажимаете Also see Topic 5C2, он прокручивается вниз и расширяет ответ 5, но когда пользователь нажимает question 5 ответ title, он сворачивает question 5 весь ответ. Затем прокрутите вверх и снова нажмите Also see Topic 5C2, он прокрутится вниз до ответа 5, но не расширит question 5 ответ.
@HassanSiddiqui это природа :target постоянного пребывания в постоянном состоянии на неопределенный срок, если не было обновления или не была нажата другая ссылка, см. Обновление.
Я не думаю, что это крайний случай, потому что сейчас мы находимся в демо-фазе, давайте предположим, что в будущем у нас будет несколько вопросов с несколькими ответами, и все ответы связаны друг с другом, тогда что произошло?
В вашем CSS вы пишете жестко закодированный CSS для триггера переключения вопросов 5, предположим, если нам нужно расширить ответы на вопросы 4, тогда мы также должны написать CSS для них. Он должен быть динамичным для каждого вопроса.
Я творил чудеса с CSS, небольшое количество JS сделало бы его действительно впечатляющим. ОП попросил чистый CSS для одной ссылки, а не для всех вопросов. Вы не ОП, задайте вопрос в своем посте о том, как стек <br>s отлично подходит для макета.
Вы уже используете JavaScript в своем атрибуте
onclick. Эти лайнеры в атрибутах в порядке? Кроме того, вы хотите щелкнуть гиперссылку, и должен открыться другой ответ?