如何解决我可以使用 CSS 选择器来创建 onclick 事件吗?
我需要代码作为 onclick 事件工作,它应该像 JS 按钮一样打开 textEditor。有可能这样做吗? :target 没有完成工作。
<!DOCTYPE html>
<html>
<body>
<style>
#textEditor {
display: none;
}
#textEditor:target {
border: 1px dashed black;
width: 1350px;
height: 600px;
display: block;
}
</style>
<a href= "#textEditor">Add Notes</a>
<div id= "textEditor" contenteditable="true"></div>
</body>
</html>
#textEditor {
display: none;
}
#textEditor:target {
border: 1px dashed black;
width: 1350px;
height: 600px;
display: block;
}
<a href="#textEditor">Add Notes</a>
<div id="textEditor" contenteditable="true"></div>
解决方法
在向您展示我将如何做之前,我真的建议您使用一些 JavaScript。也就是说,这是一个有趣的挑战,只有 CSS,我会用一个复选框来完成,因为它自然地处理了可切换状态。
#textEditor {
display: none;
}
#notes:checked ~ #textEditor{
border: 1px dashed black;
width: 1350px;
height: 600px;
display: block;
}
#notes:checked + label .add{
display: none;
}
#notes:checked + label .show{
display: inline;
}
.show{
display: none;
}
<input type="checkbox" id="notes" />
<label for="notes">
<span class="add">Add</span>
<span class="show">Hide</span> Notes
</label>
<div id="textEditor" contenteditable="true"></div>
值得注意的是,实际上我会做类似的事情
input[type="checkbox"]{ display: none; }
但我想让你看看它是如何工作的。
~
是兄弟选择器,选择上一个选择器旁边的任何元素
+
是相邻的兄弟选择器,并选择紧邻另一个的项目。
:checked
允许您设置选中的复选框的样式
鉴于您的意图是创建仅 CSS 切换,您可以使用以下几个选项;一种是使用复选框 <input>
,另一种是使用另一个 <a>
元素。
首先,<input>
方法:
#textEditor_toggle~#textEditor {
display: none;
}
#textEditor_toggle:checked~#textEditor {
border: 1px dashed black;
width: 50vw;
height: 50vh;
display: block;
margin: 1em auto;
}
#textEditor_toggle {
display: none;
}
#textEditor_toggle+label::before {
content: 'Open';
}
#textEditor_toggle:checked+label::before {
content: 'Close';
}
<input type="checkbox" id="textEditor_toggle"><label for="textEditor_toggle"> Editor</label>
<div id="textEditor" contenteditable="true" autofocus></div>
其次,使用第二个链接:
#textEditor {
display: none;
}
#textEditor:target {
border: 1px dashed black;
width: 50vw;
height: 50vh;
display: block;
grid-area: editor;
}
div {
display: grid;
grid-template-areas: "toggle" " editor";
}
a.open {
grid-area: toggle;
}
#textEditor:target+a.open {
display: none;
}
a.close {
display: none;
grid-area: toggle;
}
#textEditor:target~a.close {
display: block;
}
<div>
<div id="textEditor" contenteditable="true"></div>
<a href="#textEditor" class="open">Add Notes</a>
<a href="#" class="close">Close Notes</a>
</div>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。