8

这是一个非常快速的问题:)

只是想知道 javascript 是否有可能选择不属于 DOM 的对象......比如选择由 CSS 创建的:after或内容?:before

例如...如果我有一个 div 并通过创建一个框

div:after{
  content: '.';
  display: block;
  width: 200px;
  height: 200px;
  background: green;
}

我仍然很难理解这些元素是如何创建的,并且由于它们可以在屏幕上绘制元素但不是它们 DOM 的一部分,这是否意味着无法与它们交互?

干杯

4

2 回答 2

7

No, you won't be able to interact with them.

They're not part of the DOM, but rather are a manifestation of the style that was assigned.

If you need to add/remove the content, you can use class names.

<div id='myElem' class='withAfter'>some content</div>
div.withAfter:after{
  content: '.';
  display: block;
  width: 200px;
  height: 200px;
  background: green;
}

Then add/remove the class as needed.

于 2011-02-17T16:25:16.143 回答
2

查看文档,我发现您不能直接修改属性,也不能与通过伪选择器创建的内容进行交互。你能做的最好的就是查看属性:http: //jsfiddle.net/uaN6z/

它看起来像这样:

window.getComputedStyle(document.getElementById('test'), ':after')

我看到改变它的唯一可行方法是改变文档样式表。请参阅此 SO 答案:从 JavaScript 设置 CSS 伪类规则

祝你好运!

于 2011-02-17T16:45:02.143 回答