Web编程技术营地
研究、演示、创新

Editable Styles

撰写时间:2025-12-23

修订时间:2025-12-23

默认情况下,HTML网页中head标签的内容不会显示,置于其中的style标签的内容也不会显示。而在本文中,我们将显示其内容,并在线修改其内容。

显示style标签的内容

Visable Styles

The contents of the style tag is shown!

head { display: block; > style#css-from-tab { display: block; border: 1px solid gray; white-space: pre; font-family: monospace; padding: 1em; } } html.dark { > head > style, > body { color: #ACB7C4; background-color: #2B2B2B; } }

headstyledisplay属性值设置为block,即可显示出style标签的内容。

内容可编辑的style标签

let styleElement = document.querySelector('#css-from-tab'); styleElement.setAttribute('contenteditable', 'true');

Editable Styles

The contents of the style tag is shown and editable!

head { display: block; > style#css-from-tab { display: block; border: 1px solid gray; filter: brightness(80%); white-space: pre; font-family: monospace; padding: 1em; height: 320px; overflow: scroll; } } html.dark { > head > style, > body { color: #ACB7C4; background-color: #2B2B2B; } > body { > h1 { color: orange; } > p { font-size: 1.5em; border: 1px solid gray; } } }

通过JavaScript,设置stylecontenteditable属性值,则该标签的内容即可被编辑。

在输出面板中,将pfont-size属性值改为1em,可看出,所修改的内容立即反馈回HTML的呈现效果中。

注意到上面pCSS设置。font-sizeborder均置于一行。在border的前面输入回车,让它们断行。

出问题了。输入回车后,p的边框消失了!

造成此问题的原因是,当我们输入回车时,style中的内容不再是纯文本,打开浏览器的检查器,就会发现,浏览器自动在其内容插入了以下内容:

border: 1px solid gray; } } }

因此,它不再是有效的CSS样式内容,故而p不再有边框的设置了。

纯文本内容

最简便的解决方法是,在JavaScript中,将stylecontenteditable属性值设置为plaintext-only,正如其名,这回style将只插入纯文本的换行符\n

let styleElement = document.querySelector('#css-from-tab'); styleElement.setAttribute('contenteditable', 'plaintext-only');

Plain-text-only Editable Styles

The contents of the style tag is always plain texts now!

head { display: block; > style#css-from-tab { display: block; border: 1px solid gray; filter: brightness(80%); white-space: pre; font-family: monospace; padding: 1em; height: 320px; overflow: scroll; } } html.dark { > head > style, > body { color: #ACB7C4; background-color: #2B2B2B; } > body { > h1 { color: orange; } > p { font-size: 1.5em; border: 1px solid gray; } } }

现在,随意输入回车,试着将p的颜色也改为黄色并确认其效果。如下所示:

> p { font-size: 1.5em; border: 1px solid gray; color: green; }

结语

通过这种方式,我们可以将一些相应部位的CSS设置代码分离出来并向用户呈现,由用户自主修改其代码,且不需要额外的JavaScript代码,用户所作的修改立即生效。用户体验直接上一台阶。

当然,如果能完善必要的编辑功能,如若能提供自动缩进、代码自动完成等编辑功能,则就更完美了。

参考资源

  1. HTML Specification: Editing
  2. Editable Style Blocks