CSS伪元素内容值,通过Javascript插入的attr带有换行符

时间:2019-02-20 14:08:51

标签: javascript html css

这里也有类似的讨论:CSS data attribute new line character & pseudo-element content value

问题是,如果通过Javascript设置了attr,这将不起作用

我了解到\A在attr中不起作用,但是现在
在Java中的attr中不起作用,有什么办法可以使它工作?

const ele = document.getElementById('my-ele')
ele.classList.add('loading');
ele.setAttribute('loading-text', 'Your file is being generated...
This may take some minutes');
.loading::after {
  content: attr(loading-text);
}
<div id="my-ele"></div>

2 个答案:

答案 0 :(得分:6)

使用普通的换行符(JavaScript字符串中的\n),修复getElementById()调用(摆脱“#”),然后将white-space: pre-wrap;添加到CSS。

const ele = document.getElementById('my-ele')
ele.classList.add('loading');
ele.setAttribute('loading-text', 'Your file is being generated...\nThis may take some minutes');
.loading::after {
  white-space: pre-wrap;
  content: attr(loading-text);
}
<div id="my-ele"></div>

答案 1 :(得分:4)

这是换行符&#10\u000A与JS等价,并且可以使用。

const ele = document.getElementById('my-ele'); //removed the #
ele.classList.add('loading');
ele.setAttribute('loading-text', 'Your file is being generated...\u000AThis may take some minutes');

const ele2 = document.getElementById('my-ele2'); //removed the #
ele2.classList.add('loading');
ele2.setAttribute('loading-text', 'Your file is being generated...\nThis may take some minutes'); //as suggested by Pointy also works!
.loading::after {
white-space: pre-wrap;
  content: attr(loading-text);
}
<div id="my-ele"></div>

<div id="my-ele2"></div>