【问题标题】:Can I have an onclick effect in CSS?我可以在 CSS 中使用 onclick 效果吗?
【发布时间】:2025-11-22 16:45:01
【问题描述】:

我有一个想要在点击时更改的图像元素。

<img id="btnLeft">

这行得通:

#btnLeft:hover {
    width:70px;
    height:74px;
}

但我需要的是:

#btnLeft:onclick {
    width:70px;
    height:74px;
}

但是,显然它不起作用。是否有可能在 CSS 中具有 onclick 行为(即不使用 JavaScript)?

【问题讨论】:

  • :active 在鼠标按下时工作。根据您要执行的操作,您可以使用 CSS4 伪类 :target 使其工作。
  • :target 对 Selectors 4 来说并不陌生。它从 Selectors 3 开始可用,在撰写本文时已经推荐了一年。

标签: html css onclick


【解决方案1】:

截至 2021 年的答案:

仅使用 CSS 模拟实际 click 事件的最佳方法(实际上是唯一方法*)(而不是仅将鼠标悬停在元素上或使元素处于活动状态,而您没有 @ 987654321@) 是使用复选框破解。它通过标签的for="" 属性将label 附加到&lt;input type="checkbox"&gt; 元素来工作。

此功能具有broad browser support:checked 伪类是 IE9+)。

将相同的值应用于&lt;input&gt; 的ID 属性和伴随的&lt;label&gt;for="" 属性,您可以告诉浏览器在单击时使用:checked 伪标签重新设置样式类,这要归功于单击标签将选中和取消选中“关联”&lt;input type="checkbox"&gt;

* 您可以通过 IE7+ 中的 :active:focus 伪类模拟“选择”事件(例如,对于通常为 50px 宽的按钮,您可以在 active 时更改其宽度:@987654342 @),但那些不是真正的“点击”事件。它们在元素被选择的整个过程中都是“活动的”(例如通过 Tabbing 使用键盘),这与真正的点击事件有点不同,后者会触发一个动作 - 通常是 - @ 987654343@.


checkbox hack的基本演示(你的基本代码结构'问):

label {
    display: block;
    background: lightgrey;
    width: 100px;
    height: 100px;
}

#demo:checked + label {
    background: blue;
    color: white;
}
<input type="checkbox" id="demo"/>
<label for="demo">I'm a square. Click me.</label>

在这里,我将标签放置在标记中的输入之后。这样我就可以使用adjacent sibling selector+ 键)仅选择紧跟#demo 复选框的标签。由于:checked 伪类适用于复选框,所以#demo:checked + label 只会在复选框被选中时适用。

演示用于在点击时重新调整图像大小,这就是你的样子问:

#btnControl {
    display: none;
}

#btnControl:checked + label > img {
    width: 70px;
    height: 74px;
}
<input type="checkbox" id="btnControl"/>
<label class="btn" for="btnControl"><img src="https://placekitten.com/200/140" id="btnLeft" /></label>

话虽如此,有一些坏消息。因为标签只能是associated with one form control at a time,这意味着您不能只在&lt;label&gt;&lt;/label&gt; 标签内放一个按钮就可以收工了。但是,我们可以使用一些 CSS 使标签的外观和行为与 HTML 按钮的外观和行为非常接近。

演示用于模仿按钮点击效果,超出您的要求:

#btnControl {
    display: none;
}

.btn {
    width: 60px;
    height: 20px;
    background: silver;
    border-radius: 5px;
    padding: 1px 3px;
    box-shadow: 1px 1px 1px #000;
    display: block;
    text-align: center;
    background-image: linear-gradient(to bottom, #f4f5f5, #dfdddd);
    font-family: arial;
    font-size: 12px;
    line-height:20px;
}

.btn:hover {
    background-image: linear-gradient(to bottom, #c3e3fa, #a5defb);
}


.btn:active {
    margin-left: 1px 1px 0;
    box-shadow: -1px -1px 1px #000;
    outline: 1px solid black;
    background-image: linear-gradient(to top, #f4f5f5, #dfdddd);
}

#btnControl:checked + label {
    width: 70px;
    height: 74px;
    line-height: 74px;
}
<input type="checkbox" id="btnControl"/>
<label class="btn" for="btnControl">Click me!</label>

本演示中的大部分 CSS 仅用于设置标签元素的样式。如果您实际上不需要按钮,并且任何旧元素就足够了,那么您可以删除此演示中的几乎所有样式,类似于我上面的第二个演示。

【讨论】:

  • 太棒了!但是有没有办法在点击输入/图像/按钮以外的其他地方时也恢复更改?我使用您的示例创建了一个弹出字段,我希望它在访问者单击空白页面时消失。谢谢!
  • @mxmehl 如果你想让他们点击一个特定的位置,你可以用另一个相邻的兄弟元素来做,可能。但是,如果您希望它仅通过单击屏幕上空白的任意位置来恢复,您可能需要 JavaScript 事件侦听器。请记住,这是一种技巧,并不是创造“互动”体验的“最佳”方式;这就是 JS 的。如果您仅限于使用 CSS,这就是如何做到这一点。 :-)
  • 这个解决方案仍然不错,但是当我阅读“2017 answer”时,我期待的东西真的很酷(比如最终获得广泛浏览器支持的 CSS3 功能),而不是has been around since 2011... 有点失望。
  • @Christallkeks 如果 CSS 添加了一些东西(它可能不会;交互性超出了 CSS 的目的范围),我将更新答案以包含它。就目前而言,“2017 年答案”的标题是为了让人们知道这个答案是最新的,所以一目了然,他们不会看到答案是在 2015 年发布的事实并去“哦,不知道有没有新功能”。
  • @MuhammadSaqib 是的,它应该适用于任何支持:checked的移动浏览器。
【解决方案2】:

你会得到最接近的是:active

#btnLeft:active {
    width: 70px;
    height: 74px;
}

但是,这只会在按住鼠标按钮时应用样式。在点击时应用样式并保持其应用的唯一方法是使用一点 JavaScript。

【讨论】:

  • @Sparky672,几乎所有内容:caniuse.com/#feat=css-sel2(IE7 也支持 :active 但未列出,因为它不支持某些其他选择器)
  • @Kiyura,我猜一切,except some bugs in IE 8 and above
  • 这个答案已经过时了。有关此问题的纯 CSS 解决方案,请参阅 TylerH's answer
  • @MaximillianLaumeister 仅 CSS?需要添加一个输入和一个标签。
  • 在我申请 !important 之前,为 :active 伪类设置样式对我不起作用。当我使用 Bootstrap 时,我怀疑可能有必要覆盖其中一种内置按钮样式。
【解决方案3】:

你可以使用伪类:target来模拟点击事件,我举个例子。

#something {
  display: none;
}

#something:target {
  display: block;
}
<a href="#something">Show</a>
<div id="something">Bingo!</div>

如下所示:http://jsfiddle.net/TYhnb/

有一点需要注意,这仅限于超链接,所以如果你需要在超链接以外的地方使用,比如一个按钮,你可能想要稍微修改一下,比如将超链接的样式设置为按钮。

【讨论】:

  • 我们如何扭转行动?
  • 我认为您无法定位未显示的内容。
【解决方案4】:

如果你给元素一个tabindex,那么你可以使用:focus伪类来模拟点击。

HTML

<img id="btnLeft" tabindex="0" src="http://placehold.it/250x100" />

CSS

#btnLeft:focus{
    width:70px;
    height:74px;
}

http://jsfiddle.net/NaTj5/

【讨论】:

  • 这很好用!当您使用tabindex=-1 时,该项目仍然可以聚焦,但只能通过鼠标而不是键盘,在这种情况下更好。您还可以使用outline:0 样式在聚焦时移除蓝色边框
【解决方案5】:

编辑:在 OP 澄清他想要什么之前回答。下面是一个类似于javascripts onclick的onclick,不是:active伪类。

这只能通过 Javascript 或 Checkbox Hack 来实现

checkbox hack 本质上是让你点击一个标签,“检查”一个复选框,让你可以根据需要设置标签的样式。

demo

【讨论】:

  • 您还可以将您的输入包含在标签中,这样您就不必使用id 属性将它们绑定在一起。
【解决方案6】:

TylerH 给出了一个非常好的答案,我只需要对最后一个按钮进行视觉更新。

.btn {
    border-radius: 5px;
    padding: 10px 30px;
    box-shadow: 1px 1px 1px #000;
    background-image: linear-gradient(to bottom, #eee, #ddd);
}

.btn:hover {
    background-image: linear-gradient(to top, #adf, #8bf);
}

.btn:active {
    margin: 1px 1px 0;
    box-shadow: -1px -1px 1px #000;
}

#btnControl {
    display: block;
    visibility: hidden;
}
<input type="checkbox" id="btnControl"/>
<label class="btn" for="btnControl">Click me!</label>

【讨论】:

  • 不错:活动样式;我想要什么,但在构建它们的外观时有点匆忙。
【解决方案7】:

一个纯粹的 CSS 解决方案怎么样?

.page {
  position: fixed;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  background-color: #121519;
  color: whitesmoke;
}

.controls {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;
}

.arrow {
  cursor: pointer;
  transition: filter 0.3s ease 0.3s;
}

.arrow:active {
  filter: drop-shadow(0 0 0 steelblue);
  transition: filter 0s;
}
<body class="page">
  <div class="controls">
    <div class="arrow">
      <img src="https://i.imgur.com/JGUoNfS.png" />
    </div>
  </div>
</body>

@TylerH 的反应很好,但它是一个相当复杂的解决方案。对于那些只想要一个简单的“点击”效果和纯 CSS 而不需要一堆额外元素的人,我有一个解决方案。

我们将简单地使用 css 过渡。您可能可以对动画做类似的事情。

诀窍是更改转换的延迟,使其在用户点击时持续。

.arrowDownContainer:active,
.arrowDownContainer.clicked {
  filter: drop-shadow(0px 0px 0px steelblue);
  transition: filter 0s;
}

这里我也添加了“clicked”类,以便 javascript 也可以在需要时提供效果。我使用 0px 阴影过滤器,因为它会以这种方式突出显示给定的透明图形蓝色。

我这里有一个 0s 的过滤器,所以它不会生效。释放效果后,我可以延迟添加过渡,以便提供漂亮的“点击”效果。

.arrowDownContainer {
  cursor: pointer;
  position: absolute;
  bottom: 0px;
  top: 490px;
  left: 108px;
  height: 222px;
  width: 495px;
  z-index: 3;
  transition: filter 0.3s ease 0.3s;
}

这允许我进行设置,以便当用户单击按钮时,它会突出显示蓝色,然后慢慢淡出(当然,您也可以使用其他效果)。

虽然您在此受限于要突出显示的动画是即时的,但它仍然提供了所需的效果。您可能会将此技巧与动画一起使用,以产生更平滑的整体过渡。

【讨论】:

  • FWIW 复杂性是实现持续点击效果所必需的。如果您只想暂时做一些不保留其状态的事情,这个或许多其他解决方案都可以,我同意绝对不那么复杂。
  • 同意。总而言之,您需要最终结果,并且总是很好地了解所有选项。对于那些肯定的人来说,这是一个很棒的话题。可能值得一整篇中篇文章来介绍它们以及它们各自的好处!
【解决方案8】:

警告!下面特别简单的回答! :)

实际上可以使用 CSS(并且不使用复选框hack)尽管这里有许多(否则是正确的)答案声称,只要你只需要在悬停期间保持持久性。

所以看看 Bojangles 和 TylerH 的答案,如果它们对你有用,但如果你想要一个简单且仅 CSS 的答案,在点击后保持块可见(甚至可以通过后续点击使块消失),然后查看此解决方案。

我有类似的情况,我需要一个带有 onClick 的弹出 div,我无法添加任何 JS 或更改标记/HTML(一个真正的 CSS 解决方案),这可以通过一些警告来实现。你不能使用 :target 技巧来创建一个漂亮的弹出窗口,除非你可以更改 HTML(添加一个 'id'),这样它就被淘汰了。

在我的情况下,弹出 div 包含在另一个 div 中,我希望弹出窗口出现在另一个 div 之上,这可以使用 :active 和 :hover 的组合来完成:

/* Outer div - needs to be relative so we can use absolute positioning */
.clickToShowInfo {
    position: relative;
}
/* When clicking outer div, make inner div visible */
.clickToShowInfo:active .info { display: block; }
/* And hold by staying visible on hover */
.info:hover {
    display: block;
}
/* General settings for popup */
.info {
    position: absolute;
    top: -5;
    display: none;
    z-index: 100;
    background-color: white;
    width: 200px;
    height: 200px;
}

示例(以及允许单击弹出窗口使其消失的示例):

http://davesource.com/Solutions/20150324.CSS-Only-Click-to-Popup-Div/

我还在下面插入了一个代码 sn-p 示例,但是在 * 沙箱中的定位很奇怪,所以我不得不将“单击此处”文本放在 innerDiv 之后,这通常不需要。

/* Outer div - needs to be relative so we can use absolute positioning */
	.clickToShowInfo {
		position: relative;
	}
	/* When clicking outer div, make inner div visible */
	.clickToShowInfo:active .info { visibility: visible; }
	/* And hold by staying visible on hover */
	.info:hover {
		visibility: visible;
	}
	/* General settings for popup */
	.info {
		position: absolute;
		top: -10;
		visibility: hidden;
		z-index: 100;
		background-color: white;
		box-shadow: 5px 5px 2px #aaa;
		border: 1px solid grey;
		padding: 8px;
		width: 220px;
		height: 200px;
	}
	/* If we want clicking on the popup to close, use this */
	.info:active {
		visibility: hidden;	/* Doesn't work because DCEvent is :active as well */
		height: 0px;
		width: 0px;
		left: -1000px;
		top: -1000px;
	}
<p />
<div class="clickToShowInfo">
	<div class="info">
		Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
	</div>
	Click here to show info
</div>
<p />

【讨论】:

  • (重新:我们之前的评论讨论)信息 div 在 Firefox 上的 mouseUp 后不会保持可见。虽然它在其他浏览器(IE、Edge、Chrome)中的 mouseUp 之后确实保持可见,但当鼠标在任何其他浏览器中移出框时它不会持续存在,从而防止它被视为真正的“点击”事件(例如持续变化)。
【解决方案9】:

好吧,这可能是一个旧帖子...但它是谷歌的第一个结果,并决定在此上进行自己的组合..

首先我将使用焦点

这样做的原因是它非常适合我展示的示例,如果有人想要鼠标按下类型事件然后使用 active

HTML 代码:

<button class="mdT mdI1" ></button>
<button class="mdT mdI2" ></button>
<button class="mdT mdI3" ></button>
<button class="mdT mdI4" ></button>

CSS 代码:

/* Change Button Size/Border/BG Color And Align To Middle */
    .mdT {
        width:96px;
        height:96px;
        border:0px;
        outline:0;
        vertical-align:middle;
        background-color:#AAAAAA;
    }
    .mdT:focus {
        width:256px;
        height:256px;
    }

/* Change Images Depending On Focus */
    .mdI1       {   background-image:url('http://placehold.it/96x96/AAAAAA&text=img1');     }
    .mdI1:focus {   background-image:url('http://placehold.it/256x256/555555&text=Image+1');   }
    .mdI2       {   background-image:url('http://placehold.it/96x96/AAAAAA&text=img2');     }
    .mdI2:focus {   background-image:url('http://placehold.it/256x256/555555&text=Image+2');   }
    .mdI3       {   background-image:url('http://placehold.it/96x96/AAAAAA&text=img3');     }
    .mdI3:focus {   background-image:url('http://placehold.it/256x256/555555&text=Image+3');   }
    .mdI4       {   background-image:url('http://placehold.it/96x96/AAAAAA&text=img4');     }
    .mdI4:focus {   background-image:url('http://placehold.it/256x256/555555&text=Image+4');   }

JS FIDDLE 链接: http://jsfiddle.net/00wwkjux/

那么我为什么要在旧帖子中发布这个,因为这里的示例各不相同,我想提供一个回馈给社区,这是一个有效的示例。

正如线程创建者已经回答的那样,他们只希望效果在点击事件期间持续。现在,虽然这并不完全满足这种需求,但它已经接近了。 active 将在鼠标按下时动画,并且您需要持续更长时间的任何更改都需要使用 javascript 完成。

【讨论】:

  • 对于任何阅读的人,无论如何都要让它切换?还是对 css 的要求太高了?
  • 据我所知,焦点/活动/悬停几乎与 css 一样接近。您也许可以使用选项/选择类型的代码做一些花哨的事情。但还没有尝试过/需要那个
【解决方案10】:

我遇到了一个问题,该元素在悬停时必须为红色,而在悬停时单击时必须为蓝色。要使用 css 实现这一点,您需要例如:

h1:hover { color: red; } 
h1:active { color: blue; }

<h1>This is a heading.</h1>

我挣扎了一段时间,直到我发现 CSS 选择器的顺序是我遇到的问题。问题是我切换了位置并且活动选择器不起作用。然后我发现:hover先去,然后:active

【讨论】:

    【解决方案11】:

    我有下面的鼠标悬停和鼠标点击代码,它可以工作:

    //For Mouse Hover
    .thumbnail:hover span{ /*CSS for enlarged image*/
        visibility: visible;
        text-align:center;
        vertical-align:middle;
        height: 70%;
        width: 80%;
        top:auto;
        left: 10%;
    }
    

    当您单击它时,此代码会隐藏图像:

    .thumbnail:active span {
        visibility: hidden;
    }
    

    【讨论】:

      【解决方案12】:

      在我们进入问题的核心之前,让我们把它弄好以备将来参考 - 您应该使用 JavaScript 处理 click 事件。

      document.querySelector('img').addEventListener('click', function() {
        this.classList.toggle('large');
      });
      .large {
        width: 75px;
        height: 75px;
      }
      &lt;img src="https://i.stack.imgur.com/5FBwB.png" alt="Heart"&gt;

      但是,如果由于某种原因不能使用 JavaScript,有两种常用方法可以模拟 click 事件并使用 CSS 创建切换按钮。

      复选框破解?

      checkbox hack 不是一个好习惯:

      • 它在语义上不正确,这就是它被称为 hack 的原因。
      • 它会导致键盘用户和屏幕阅读器的可访问性问题。
      • 它限制了您的 HTML 结构,因为复选框必须是您要控制的元素的前一个兄弟元素。
      • 您无法控制&lt;html&gt;&lt;body&gt; 元素。

      :目标选择器?

      :target CSS 伪类表示一个唯一元素(目标元素),其中 id 与 URL 的片段匹配。正如您在以下示例中看到的,执行者的 href#fade-out 与目标元素的 id 匹配。

      a {
        display: inline-block;
        padding: 8px 12px;
        border-radius: 5px;
        background: linear-gradient(#eee, #ddd);
        color: #333;
        font: bold 12px Verdana;
        text-shadow: 0 1px white;
        text-decoration: none;
      }
      
      p {
        font: 13px/1.5 Arial;
        padding: 1em;
        background: aqua;
        transition: 1s linear;
      }
      
      :target {
        opacity: 0;
      }
      <a href="#fade-out">Fade out</a>
      
      <p id="fade-out">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

      :target 选择器可用于设置当前活动目标元素的样式。这意味着它就像一个单选按钮:只能同时选择给定组中的一个。

      body {
        display: inline-grid;
        font: 16px "Times New Roman";
      }
      
      a {
        padding-left: 24px;
        margin: 0 2em 1em 0;
        justify-self: start;
        background: radial-gradient(circle 7px at 8px, #dedede 7px, transparent 8px);
        color: #333;
        text-decoration: none;
      }
      
      a:hover {
        background: radial-gradient(circle 7px at 8px, #ccc 7px, transparent 8px);
      }
      
      a:target {
        background: radial-gradient(circle 7px at 8px, dodgerBlue 4px, white 5px 6px, dodgerBlue 7px, transparent 8px);
      }
      
      div {
        grid-area: 1 / 2 / 7;
        width: 154px;
        height: 154px;
        text-align: center;
        background: aqua;
        color: black;
        border-radius: 50%;
        transition: 0.3s linear;
      }
      
      #rotate90:target ~ div {
        transform: rotate(90deg);
      }
      
      #rotate180:target ~ div {
        transform: rotate(180deg);
      }
      
      #rotate270:target ~ div {
        transform: rotate(270deg);
      }
      
      #rotate360:target ~ div {
        transform: rotate(360deg);
      }
      <a href="#rotate0" id="rotate0">0°</a>
      <a href="#rotate90" id="rotate90">90°</a>
      <a href="#rotate180" id="rotate180">180°</a>
      <a href="#rotate270" id="rotate270">270°</a>
      <a href="#rotate360" id="rotate360">360°</a>
      
      <div>•</div>

      Q.如何创建一个切换按钮?
      A.基本上,它是这样工作的:你使用两个超链接,一个“doer”和一个“取消者”。 doer 指向目标元素,而指向无处的 undoer 则反转效果。

      以下演示展示了:target 选择器的潜力,并让您了解如何使用它。

      为前一个兄弟设置样式

      div {
        width: 200px;
        height: 200px;
        background: #dedede;
        transition: 0.3s ease-in-out;
      }
      
      a {
        display: inline-flex;
        align-items: center;
        column-gap: 1ch;
        margin-top: 1em;
        font: 16px Arial;
        color: #333;
        text-decoration: none;
      }
      
      a::before {
        content: "✔";
        font-size: 13px;
        width: 1.2em;
        line-height: 1.2em;
        text-align: center;
        background: #dedede;
        color: transparent;
      }
      
      .undoer::before {
        background: dodgerBlue;
        color: white;
        text-shadow: 0 2px black;
      }
      
      .doer:hover::before {
        background: #ccc;
      }
      
      :target {
        border-radius: 50%;
      }
      
      .undoer,
      :target ~ .doer {
        display: none;
      }
      
      :target ~ .undoer {
        display: inline-flex;
      }
      <div id="circle"></div>
      
      <a href="#circle" class="doer">Circle</a>
      <a href="#square" class="undoer">Circle</a>

      为下一个兄弟设置样式

      链接甚至可以定位相同的锚元素。

      body {
        text-align: center;
      }
      
      h1 {
        font-size: 24px;
      }
      
      a {
        display: inline-block;
        padding: 8px 12px;
        border-radius: 5px;
        margin-bottom: 1em;
        background: linear-gradient(#eee, #ddd);
        color: #333;
        font: bold 12px Verdana;
        text-shadow: 0 1px white;
        text-decoration: none;
      }
      
      [class]:not(.yellow) {
        color: white;
        text-shadow: 0 1px black;
      }
      
      .red {
        background: red;
      }
      
      .orange {
        background: orange;
      }
      
      .yellow {
        background: yellow;
      }
      
      .green {
        background: green;
      }
      
      .blue {
        background: blue;
      }
      
      .indigo {
        background: indigo;
      }
      
      .violet {
        background: violet;
      }
      
      div {
        width: 600px;
        height: 400px;
        margin: 0 auto;
        background: #eee;
        transition: 0.3s ease-in-out;
      }
      
      [class],
      :target {
        display: none;
      }
      
      :target + a {
        display: inline-block;
      }
      
      #red:target ~ div {
        background: red;
      }
      
      #orange:target ~ div {
        background: orange;
      }
      
      #yellow:target ~ div {
        background: yellow;
      }
      
      #green:target ~ div {
        background: green;
      }
      
      #blue:target ~ div {
        background: blue;
      }
      
      #indigo:target ~ div {
        background: indigo;
      }
      
      #violet:target ~ div {
        background: violet;
      }
      <h1>?</h1>
      
      <a href="#red" id="red">Red</a>
      <a href="#cancel" class="red">Red</a>
      
      <a href="#orange" id="orange">Orange</a>
      <a href="#cancel" class="orange">Orange</a>
      
      <a href="#yellow" id="yellow">Yellow</a>
      <a href="#cancel" class="yellow">Yellow</a>
      
      <a href="#green" id="green">Green</a>
      <a href="#cancel" class="green">Green</a>
      
      <a href="#blue" id="blue">Blue</a>
      <a href="#cancel" class="blue">Blue</a>
      
      <a href="#indigo" id="indigo">Indigo</a>
      <a href="#cancel" class="indigo">Indigo</a>
      
      <a href="#violet" id="violet">Violet</a>
      <a href="#cancel" class="violet">Violet</a>
      
      <div></div>

      替换一个元素

      您可能已经注意到,您可以将一个元素完全替换为另一个元素。

      .undoer,
      :target {
        display: none;
      }
      
      :target + .undoer {
        display: inline;
      }
      <a href="#on" title="Turn on the light" id="on"><img src="https://i.stack.imgur.com/nuKgJ.png" alt="Light on"></a>
      <a href="#off" title="Turn off the light" class="undoer"><img src="https://i.stack.imgur.com/3DLVM.png" alt="Light off"></a>

      您甚至可以在锚点内嵌套块级元素。

      如果您希望在从 doer 切换到 undoer 时具有过渡效果,请在第一个上使用 position: absolute,在第二个上使用 visibility: hidden

      a {
        display: block;
        box-sizing: border-box;
        width: 64px;
        padding-left: 33px;
        border-radius: 16px;
        background: radial-gradient(circle 12px, white 100%, transparent calc(100% + 1px)) #ccc -16px;
        font: bold 12px/32px Verdana;
        color: white;
        text-shadow: 0 1px black;
        text-decoration: none;
        transition: 0.3s ease-in-out;
        transition-property: padding-left, background-color, background-position;
      }
      
      #start {
        position: absolute;
      }
      
      :target,
      :target + .undoer {
        padding-left: 8px;
        background-color: dodgerBlue;
        background-position: 16px;
      }
      
      .undoer,
      :target {
        visibility: hidden;
      }
      
      :target + .undoer {
        visibility: visible;
      }
      <a href="#start" id="start">OFF</a>
      <a href="#stop" class="undoer">ON</a>

      隐藏和显示内容

      这是一个导航菜单。

      html,
      body {
        margin: 0;
        padding: 0;
      }
      
      header {
        display: flex;
        line-height: 50px;
        background: linear-gradient(#999, #333);
        color: white;
      }
      
      a {
        color: inherit;
        text-decoration: none;
      }
      
      header > a,
      header h1 {
        font-size: 26px;
        font-family: 'Times New Roman';
        text-shadow: 0 3px black;
      }
      
      header > a {
        width: 50px;
        text-align: center;
      }
      
      header h1 {
        margin: 0;
        letter-spacing: 1px;
      }
      
      nav {
        position: absolute;
        top: 50px;
        background: #333;
        visibility: hidden;
        transform: translateX(-100%);
        transition: 280ms ease-out 120ms;
      }
      
      nav a {
        display: block;
        padding: 1em;
        font: bold 12px Verdana;
        transition: inherit;
      }
      
      nav a:not(:last-child) {
        border-bottom: 1px solid black;
      }
      
      nav a:hover,
      #current {
        background: #A00;
      }
      
      .undoer,
      :target {
        display: none;
      }
      
      :target + .undoer {
        display: block;
      }
      
      :target ~ nav {
        visibility: visible;
        transform: none;
      }
      
      main {
        padding: 16px;
        font: 13px Arial;
        color: #333;
      }
      
      main h1 {
        font-size: 1.5em;
      }
      
      p {
        line-height: 1.5;
      }
      <header>
        <a href="#open" id="open">☰</a>
        <a href="#close" class="undoer">✕</a>
        <h1>? Music School</h1>
        <nav>
          <a href="#" id="current">Home</a>
          <a href="#">Instruments</a>
          <a href="#">Online Lessons</a>
          <a href="#">Register</a>
          <a href="#">Contact</a>
        </nav>
      </header>
      <main>
        <h1>Home</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
      </main>

      这是一个常见问题页面。

      body {
        font: 16px Arial;
        color: #333;
        max-width: 600px;
        margin: 1em auto;
      }
      
      h1 {
        text-align: center;
        font-family: "Times New Roman";
      }
      
      p {
        display: none;
        padding: 12px;
        border: 2px solid #dedede;
        border-top: 0;
        margin: 0;
        font-size: 13px;
        line-height: 1.5;
      }
      
      a {
        display: flex;
        align-items: center;
        column-gap: 12px;
        padding: 12px;
        margin-top: 1em;
        background: #dedede;
        color: inherit;
        font-weight: bold;
        line-height: 1.5;
        text-shadow: 0 1px white;
        text-decoration: none;
      }
      
      a::before {
        content: "➕";
        padding: 3px;
        background: #eee;
        font-weight: initial;
      }
      
      a[href="#close"]::before {
        content: "➖";
      }
      
      a:hover::before {
        background: #fff;
      }
      
      a[href="#close"],
      a:target {
        display: none;
      }
      
      a:target + a {
        display: flex;
      }
      
      a:target + a + p {
        display: block;
      }
      <h1>Frequently Asked Questions</h1>
      
      <a href="#open1" id="open1">How do we get more energy from the sun?</a>
      <a href="#close">How do we get more energy from the sun?</a>
      <p>Dwindling supplies of fossil fuels mean we’re in need of a new way to power our planet. Our nearest star offers more than one possible solution. We’re already harnessing the sun’s energy to produce solar power. Another idea is to use the energy in sunlight to split water into its component parts: oxygen, and hydrogen, which could provide a clean fuel for cars of the future. Scientists are also working on an energy solution that depends on recreating the processes going on inside stars themselves – they’re building a nuclear fusion machine. The hope is that these solutions can meet our energy needs.</p>
      
      <a href="#open2" id="open2">What's so weird about prime numbers?</a>
      <a href="#close">What's so weird about prime numbers?</a>
      <p>The fact you can shop safely on the internet is thanks to prime numbers – those digits that can only be divided by themselves and one. Public key encryption – the heartbeat of internet commerce – uses prime numbers to fashion keys capable of locking away your sensitive information from prying eyes. And yet, despite their fundamental importance to our everyday lives, the primes remain an enigma. An apparent pattern within them – the Riemann hypothesis – has tantalised some of the brightest minds in mathematics for centuries. However, as yet, no one has been able to tame their weirdness. Doing so might just break the internet.</p>
      
      <a href="#open3" id="open3">Can computers keep getting faster?</a>
      <a href="#close">Can computers keep getting faster?</a>
      <p>Our tablets and smartphones are mini-computers that contain more computing power than astronauts took to the moon in 1969. But if we want to keep on increasing the amount of computing power we carry around in our pockets, how are we going to do it? There are only so many components you can cram on to a computer chip. Has the limit been reached, or is there another way to make a computer? Scientists are considering new materials, such as atomically thin carbon – graphene – as well as new systems, such as quantum computing.</p>
      
      <a href="#open4" id="open4">When can I have a robot butler?</a>
      <a href="#close">When can I have a robot butler?</a>
      <p>Robots can already serve drinks and carry suitcases. Modern robotics can offer us a “staff” of individually specialised robots: they ready your Amazon orders for delivery, milk your cows, sort your email and ferry you between airport terminals. But a truly “intelligent” robot requires us to crack artificial intelligence. The real question is whether you’d leave a robotic butler alone in the house with your granny. And with Japan aiming to have robotic aides caring for its elderly by 2025, we’re thinking hard about it now.</p>
      
      <a href="#open5" id="open5">What's at the bottom of the ocean?</a>
      <a href="#close">What's at the bottom of the ocean?</a>
      <p>Ninety-five per cent of the ocean is unexplored. What’s down there? In 1960, Don Walsh and Jacques Piccard travelled seven miles down, to the deepest part of the ocean, in search of answers. Their voyage pushed the boundaries of human endeavour but gave them only a glimpse of life on the seafloor. It’s so difficult getting to the bottom of the ocean that for the most part we have to resort to sending unmanned vehicles as scouts. The discoveries we’ve made so far – from bizarre fish such as the barreleye, with its transparent head, to a potential treatment for Alzheimer’s made by crustaceans – are a tiny fraction of the strange world hidden below the waves.</p>
      
      <a href="#open6" id="open6">What's at the bottom of a black hole?</a>
      <a href="#close">What's at the bottom of a black hole?</a>
      <p>It’s a question we don’t yet have the tools to answer. Einstein’s general relativity says that when a black hole is created by a dying, collapsing massive star, it continues caving in until it forms an infinitely small, infinitely dense point called a singularity. But on such scales quantum physics probably has something to say too. Except that general relativity and quantum physics have never been the happiest of bedfellows – for decades they have withstood all attempts to unify them. However, a recent idea – called M-Theory – may one day explain the unseen centre of one of the universe’s most extreme creations.</p>
      
      <a href="#open7" id="open7">How do we solve the population problem?</a>
      <a href="#close">How do we solve the population problem?</a>
      <p>The number of people on our planet has doubled to more than 7 billion since the 1960s and it is expected that by 2050 there will be at least 9 billion of us. Where are we all going to live and how are we going to make enough food and fuel for our ever-growing population? Maybe we can ship everyone off to Mars or start building apartment blocks underground. We could even start feeding ourselves with lab-grown meat. These may sound like sci-fi solutions, but we might have to start taking them more seriously.</p>

      切换到全新的样式表

      您可以定位一个元素及其所有后代元素并为其设置样式。例如,让我们定位 &lt;body&gt; 元素并切换暗/亮模式。

      body,
      a,
      h2 {
        transition: 0.3s linear;
      }
      
      body {
        font: 13px Arial;
        background: white;
        color: #333;
      }
      
      a {
        font-size: 16px;
        text-decoration: none;
      }
      
      main {
        column-count: 3;
        column-gap: 2em;
        padding: 0 1em;
      }
      
      h1 {
        column-span: all;
        text-align: center;
      }
      
      h2:nth-of-type(1) {
        margin-top: 0;
      }
      
      p {
        line-height: 1.5;
      }
      
      :target {
        background: #333;
        color: white;
      }
      
      .doer {
        position: absolute;
      }
      
      .undoer,
      :target .doer {
        visibility: hidden;
        opacity: 0;
      }
      
      :target .undoer {
        visibility: visible;
        opacity: 1;
      }
      
      :target h2:nth-of-type(1) {
        color: red;
      }
      
      :target h2:nth-of-type(2) {
        color: green;
      }
      
      :target h2:nth-of-type(3) {
        color: blue;
      }
      <body id="dark">
      <a href="#dark" title="Dark mode" class="doer">?</a>
      <a href="#light" title="Light mode" class="undoer">☀️</a>
      <main>
      <h1>Primary Colors</h1>
      <h2>Red</h2>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
      <h2>Green</h2>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
      <h2>Blue</h2>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
      </main>
      </body>

      ???

      您可以使用:target 选择器完成的可能性和有趣的事情列表中缺少任何功能吗?请在下面的 cmets 中分享。

      【讨论】:

        【解决方案13】:

        你可以使用:target

        或按类名过滤,使用.classname:target

        或使用#idname:target按ID名称过滤

        #id01:target {      
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .msg {
            display:none;
        }
        
        .close {        
            color:white;        
            width: 2rem;
            height: 2rem;
            background-color: black;
            text-align:center;
            margin:20px;
        }
          
        <a href="#id01">Open</a>
        
        <div id="id01" class="msg">    
            <a href="" class="close">&times;</a>
            <p>Some text. Some text. Some text.</p>
            <p>Some text. Some text. Some text.</p>
        </div>

        【讨论】:

        • 已经发布了一个显示如何使用:target的答案,所以不需要再做一个了。此外,提问者询问如何产生“点击”效果,而不是显示/隐藏其他元素。
        • 这更像是一种“onload”而不是“onclick”效果。
        最近更新 更多