可以仅使用CSS(没有JavaScript代码)隐藏和显示文本吗?

时间:2018-08-22 04:00:52

标签: css

是否可以仅使用CSS链接显示和隐藏文本-完全不使用JavaScript?

例如:在this page

请注意“更多”链接。单击它时,它将取消隐藏文本。这个特定的示例是JavaScript,但是我不确定是否可以使用纯CSS来完成。

9 个答案:

答案 0 :(得分:106)

<details> element,它尚未内置在Edge中:

<details>
  <summary>more <!-- a bad summary --></summary>
  <p>Some content</p>
</details>

我不确定跨浏览器保持样式一致有多么困难。

有一个常见的复选框黑客(可以隐藏该复选框,并且可以将标签设置为看起来像任何东西的样式):

#more:not(:checked) ~ #content {
  display: none;
}
<input id="more" type="checkbox" /> <label for="more">more</label>

<p id="content">Some content</p>

但并不总是(也许曾经?嗯)适合使用它;您通常可以在JavaScript无法加载时重新显示内容,并具有“更多”链接链接。

也有:target,但是它可能更不合适,因为在关闭机制中很难建立它。

#content {
  display: none;
}

#content:target {
  display: block;
}

#less {
  display: none;
}

#content:target ~ #less {
  display: block;
}
<a href="#content" id="more">More</a>
<p id="content">Lorem ipsum</p>
<a href="#" id="less">Less</a>

答案 1 :(得分:39)

,使用纯CSS可以实现。通过将复选框的 :checked 属性与 <label> 元素的for结合使用,您可以单击元素属性。

由于该复选框可以未选中,因此您可以通过将visibility: hidden添加到源自:checked的元素中来切换可见性(一旦再次单击该复选框,此伪选择器将无效,并且CSS选择器将不再与目标匹配)。

可以使用<label>属性将其扩展到for,以便您可以完全隐藏复选框本身,并直接将自己的样式应用于<label>。 / p>

以下内容在单击toggle元素时利用 adjacent sibling combinator (+) 来切换类<label>

input[type="checkbox"] {
  display: none; /* Hide the checkbox */
}

/* This is tied to the invisible checkbox */
label {
    background-color: #4CAF50;
    border: 2px solid black;
    border-radius: 20px;
    color: white;
    padding: 15px 32px;
    text-align: center;
    font-size: 16px;
    display: inline-block;
    margin-bottom: 20px;
    cursor: pointer;
    user-select: none;
}

/* The target element to toggle */
input[type="checkbox"]:checked + label + .toggle {
  visibility: hidden;
}
<input type="checkbox" id="checkbox" />
<label for="checkbox">Click me to toggle the content</label>
<div class="toggle">CONTENT</div>

答案 2 :(得分:16)

是的,您仅使用CSS即可轻松完成此操作。请参考以下代码:

* {
  box-sizing: border-box;
}

body {
  background-color: #646464;
  color: #fff;
}

header {
  background-color: rgba(0, 0, 0, 0.5);
  font-size: 1.5em;
  text-align: center;
  padding: 1em;
}

.panel-wrapper {
  position: relative;
}

.btn {
  color: #fff;
  background: #000;
  border-radius: 1.5em;
  left: 30%;
  padding: 1em;
  text-decoration: none;
  width: 40%;
}

.show,
.hide {
  position: absolute;
  bottom: -1em;
  z-index: 100;
  text-align: center;
}

.hide {
  display: none;
}

.show:target {
  display: none;
}

.show:target~.hide {
  display: block;
}

.show:target~.panel {
  max-height: 2000px;
}

.show:target~.fade {
  margin-top: 0;
}

.panel {
  position: relative;
  margin: 2em auto;
  width: 70%;
  max-height: 100px;
  overflow: hidden;
  transition: max-height .5s ease;
}

.fade {
  background: linear-gradient(to bottom, rgba(100, 100, 100, 0) 0%, #646464 75%);
  height: 100px;
  margin-top: -100px;
  position: relative;
}
<!DOCTYPE html>
<html lang='en' class=''>

<head>
  <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css'>
</head>

<body>
  <header>CSS Only: Show More</header>
  <div class="panel-wrapper">
    <a href="#show" class="show btn" id="show">Show Full Article</a>
    <a href="#hide" class="hide btn" id="hide">Hide Full Article</a>
    <div class="panel">
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In pharetra consectetur accumsan. Vestibulum vitae ipsum euismod, tempus ligula non, tempus lacus. Phasellus at pellentesque ex. Praesent at ipsum dui. Cras lectus neque, bibendum ac diam
        a, elementum tristique felis. Sed iaculis, diam at vehicula lacinia, odio urna tincidunt felis, sit amet scelerisque urna erat non leo. Pellentesque vel leo vitae tellus bibendum viverra.</p>
      <p>Donec id ultrices mi. Suspendisse potenti. Pellentesque cursus sagittis lacinia. Mauris elit sem, eleifend nec facilisis eget, fermentum sed odio. Nam aliquam massa nec leo tincidunt rhoncus. Integer tincidunt finibus tincidunt. Maecenas aliquam
        fermentum nisi, vitae mattis neque vehicula vitae.</p>
      <p>Nam orci purus, consequat sed lorem id, lacinia efficitur lorem. Vestibulum id quam ut elit congue varius. Donec justo augue, rhoncus non nisl ut, consectetur consequat velit. In hac habitasse platea dictumst. In hac habitasse platea dictumst. Aliquam
        auctor sapien lorem, at vestibulum justo congue vel. Duis volutpat, lorem quis tincidunt ornare, felis tortor posuere tellus, nec pretium neque velit vulputate libero.</p>
      <p>Morbi tortor tortor, auctor porttitor felis in, eleifend cursus ante. Nullam pellentesque lorem ipsum, in fringilla enim suscipit cursus. Pellentesque feugiat volutpat congue. Donec ac ante elit. Quisque ornare lacus dui, id commodo tortor lacinia
        nec. Curabitur dignissim magna sagittis neque aliquam porttitor. Aenean sit amet tincidunt risus.</p>
      <p>Cras feugiat, sapien luctus congue gravida, enim enim tristique nisl, vel porta lacus ante vitae dolor. Duis at nisl sed lectus imperdiet congue. Vestibulum pellentesque finibus ligula, sit amet elementum enim dignissim eget. Nullam bibendum justo
        eros, in placerat est ullamcorper nec. Donec blandit accumsan venenatis. Vivamus nec elit arcu. Morbi ultrices blandit sapien eget aliquam. Pellentesque placerat et libero a sodales. Donec eget erat ac velit maximus ullamcorper. Nulla laoreet
        dolor in purus sollicitudin varius. Duis eu erat ut magna lobortis rhoncus ac at lacus. Nullam in mi sed sem porttitor molestie. Aenean auctor dui in neque vulputate, in mattis purus tristique. Aliquam egestas venenatis ultricies. Nam elementum
        ante libero, nec dictum erat mollis dapibus. Phasellus pharetra euismod nibh, sit amet lobortis odio.</p>
      <p>Sed bibendum dapibus leo eu facilisis. Cras interdum malesuada diam id lobortis. Phasellus tristique odio eget placerat ornare. Phasellus nisl nulla, auctor convallis turpis tempus, molestie blandit urna. Nullam accumsan tellus massa, at tincidunt
        metus imperdiet sed. Donec sed imperdiet quam, id dignissim dolor. Curabitur mollis ultricies tempor. Morbi porttitor, turpis et dignissim aliquam, nunc lacus dignissim massa, a consequat nibh est vel turpis. Pellentesque blandit, ante vehicula
        sollicitudin imperdiet, tellus urna fringilla diam, id tempor neque augue eu nisl. Quisque eu sem posuere, vehicula risus ut, ullamcorper massa. Fusce vulputate bibendum erat, vel dapibus dui consectetur nec. Donec mauris mauris, egestas non malesuada
        non, finibus nec lacus. Duis at mauris tincidunt, accumsan augue non, vestibulum libero.</p>
      <p>Vestibulum fermentum vulputate lectus, at sollicitudin diam laoreet vitae. Aliquam erat volutpat. Nulla condimentum, arcu nec suscipit ultrices, urna tortor rutrum purus, sed mollis lacus ligula vitae justo. Duis vitae malesuada sem, eget finibus
        nibh. Etiam facilisis, urna ac blandit molestie, quam velit congue nibh, ac.</p>

    </div>
    <!-- end panel -->
    <div class="fade"></div>
  </div>
  <!-- end panel-wrapper -->

</body>

</html>

答案 3 :(得分:14)

您可以隐藏一个复选框,但允许通过其关联的<label>元素对其进行选中/取消选中。

根据是否选中该复选框,您可以隐藏/显示其他文本,甚至可以将标签的文本从“更多”更改为“更少”。

我在CSS中添加了一些其他细节,以便使每个定义的意图更加明确。

1。一键切换“更多” /“减少”按钮:

.more-text, #more-checkbox {          /* Hide the second paragraph and checkbox */
  display: none;
}

input:checked ~ .more-text {          /* Show the second paragraph when checked */
  display: block;
}

.more-label::after {                  /* Label underline, hand cursor, color */
  cursor: pointer;
  text-decoration: underline;
  color: #666;
}

input ~ .more-label::after {          /* Set label text to "More" by default */
  content: 'More';
}

input:checked ~ .more-label::after {  /* Set label text to "Less" when checked */
  content: 'Less';
}
<p>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ullamcorper, arcu ut facilisis interdum, lacus felis fringilla nulla, vel scelerisque massa quam vel leo.
</p>

<input type="checkbox" id="more-checkbox" />
<label class="more-label" for="more-checkbox"></label>

<p class="more-text">
  Sed a ullamcorper ex. In elementum purus ullamcorper justo gravida aliquet. Aliquam erat volutpat. Maecenas in ante quam.
</p>


2。顶部带有“更多”按钮,底部带有“较少”按钮:

.more-text, #more-checkbox, .less-label {
  display: none;
}

.more-label, .less-label {          
  cursor: pointer;
  text-decoration: underline; 
  color: #666;
}

input:checked ~ .more-text, input:checked ~ .less-label {
  display: block;
}

input:checked ~ .more-label {
  display: none;
}
<p>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ullamcorper, arcu ut facilisis interdum, lacus felis fringilla nulla, vel scelerisque massa quam vel leo.</p>

<input type="checkbox" id="more-checkbox" />
<label class="more-label" for="more-checkbox">More</label>

<p class="more-text">
  Sed a ullamcorper ex. In elementum purus ullamcorper justo gravida aliquet. Aliquam erat volutpat. Maecenas in ante quam.
</p>

<label class="less-label" for="more-checkbox">Less</label>

答案 4 :(得分:11)

从技术上讲,可以根据单击按钮或链接的时间来切换文本的可见性,如下所示:

.hidden-text {
  display: none;
}

.toggle-text:focus + .hidden-text {
  display: block;
}
<p>
  This is an example with no hidden content until you... <a href="#" class="toggle-text">read more</a>!
  <span class="hidden-text">Now I'm visible!!!</span>
</p>

话虽这么说,但我强烈建议您熟悉JavaScript,因为使用JavaScript来解决诸如此类的问题要简单得多,并且可以增加灵活性。

答案 5 :(得分:10)

是的,您只能通过使用HTML和CSS来做到这一点。

body { padding: 20px; }

div { margin-top: 10px; border: 1px solid black; width: 200px; height: 100px;
    padding: 5px;
}
input:checked + label + div { display: none; }
input + label:after { content: " To Hide"; }
input:checked + label:after { content: " To Show"; }

label {
    background-color: yellow;
    box-shadow: inset 0 2px 3px rgba(255,255,255,0.2), inset 0 -2px 3px rgba(0,0,0,0.2);
    border-radius: 4px;
    font-size: 16px;
    display: inline-block;
    padding: 2px 5px;
    cursor: pointer;
}
<input type='checkbox' style='display: none' id=cb>
<label for=cb>Click Here</label>
<div>
    Hello. This is some stuff.
</div>

答案 6 :(得分:3)

现在您也可以仅使用CSS隐藏/显示文本! 如果您正在使用文本输入,并且想根据输入框的状态显示/隐藏文本,则可以对:placeholder-shown<input>使用新的CSS伪类<textarea>。 这是上述伪类的示例/演示!

/* Some base style  */
.app {
  margin: 10px auto;
  padding: 10px;
}

code {
  background-color: lightgray;
  padding: 4px;
}

input {
  padding: 5px 10px;
}

input:focus {
  outline: none;
}

/* When there is something in input box give 
  it a solid blue border */

input:not(:placeholder-shown) {
  border: solid 2px #42A5F5
}

/* Hide the p initially */
p {
  background-color: #F0F4C3;
  padding: 5px;
  opacity: 0;
  transition: all 300ms ease-in-out;
}


/* Show the p when the placeholder is not shown. 
  i.e. Something is in the input box and placeholder is gone */
input:not(:placeholder-shown)+p {
  opacity: 1
}
<div class="app">
  <h1>Hide/Show Text using input's <code>:placehoder-shown</code> psuedo class!</h1>
  <label for="name">Enter your name</label>
  <input type="text" id="name" placeholder="Your Name">
  <p class="msg">Well done!</p>
</div>

此处Link是MDN文档。

  

这是一项实验技术   在生产环境中使用此功能之前,请仔细检查浏览器兼容性表。

答案 7 :(得分:-1)

也许有人会发现此解决方案更直观,更易于实现。这样做的机制是链接以自身为目标,在这种情况下,很容易选择DOM接下来的内容。

.toggle-hide,
.toggle-content {
  display: none;
}
.toggle-show:target + .toggle-hide,
.toggle-show:target + .toggle-hide + .toggle-content {
  display: block;
}
.toggle-show:target {
  display: none;
}
<a id="target" class="toggle-show" href="#target">Show</a>
<a class="toggle-hide" href="#" >Hide</a>
<p class="toggle-content">Lorem ipsum</p>

答案 8 :(得分:-3)

使用"display: none;" attribute.