简体   繁体   English

在 ::before 或 ::after 伪元素中选择文本

[英]Select text in ::before or ::after pseudo-element

Look this very simple code看看这个非常简单的代码

<!DOCTYPE html>
<html>
<head>
<style>
p::before {
    content: "Before - ";
}
</style>
</head>
<body>
<p>Hello</p>
<p>Bye</p>   
</body>
</html>

Css adds ¨Before -" at the start of every <P> and renders like this Css 在每个<P>的开头添加¨Before -"并像这样呈现

在此处输入图片说明

If you use your mouse to select the text (for copy paste) you can select the original text, but not the Before or Aftter text added by css.如果使用鼠标选择文本(用于复制粘贴),则可以选择原始文本,但不能选择 css 添加的 Before 或 After 文本。

在此处输入图片说明

I have a very specific requirement where I need to allow users to select with the mosue the Before text.我有一个非常具体的要求,我需要允许用户使用 mosue 选择 Before 文本。 How would you do it?你会怎么做?

This cannot be done within an HTML page, but as a hack, if you need to copy/paste pseudo elements, you can export the page to PDF and copy from it.这不能在 HTML 页面中完成,但作为一种技巧,如果您需要复制/粘贴伪元素,您可以将页面导出为 PDF 并从中复制。 In Chrome, for example, you can copy page's content from print preview.例如,在 Chrome 中,您可以从打印预览中复制页面内容。

你不能,之前和之后的伪类不打算用于这个目的。

If users need to select the generated text, it should be considered content (and in the HTML), not presentation (and hidden in the CSS).如果用户需要选择生成的文本,则应将其视为内容(并在 HTML 中),而不是表示(并隐藏在 CSS 中)。

Don't use ::before or ::after , use HTML.不要使用::before::after ,使用 HTML。

You could use JavaScript to insert it (if that would help):您可以使用 JavaScript 插入它(如果有帮助的话):

var text = document.createTextNode('Before - ');
Array.prototype.forEach.call(document.getElementsByTagName('p'), function (p) {
    p.insertBefore(text.cloneNode(), p.firstChild);
});

This way the text itself is present in the DOM, unlike generated content from CSS.这样,文本本身就存​​在于 DOM 中,与从 CSS 生成的内容不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM