我的测试表明,:target
选择器只在页面加载时影响 DOM 中存在的元素。我说得对吗?
我无法在此处创建代码段,因为我无法使用哈希 (#
) 调用 iframe 的代码段,因此您可以在此处查看问题:
http://output.jsbin.com/vixave#new_element
HTML 按钮
<button onclick="addElement()">Add element</button>
CSS
div:target {
background:red;
color:#fff;
}
Javascript
function addElement() {
document.body.innerHTML += '<div id="new_element">New element</div><br /><a href="#new_element">highlight</a>';
}
在这个演示中你可以看到当你点击按钮并且div #new_element
被添加到body之后,他并没有“得到”样式。只有当您单击再次调用相同 URL 的链接时,才会应用该样式。
更新
进一步@BoltClock 的评论,这发生在 Chrome 和 FireFox 中,但在 IE 中(太奇怪了)它按预期工作。
最佳答案
当存在片段(URL 中 #
之后的字符串)时应用 :target
选择器的样式是正确的行为。
可以在 W3C Selectors 中找到指定的行为和 HTML5规范。
6.6.2. The target pseudo-class :target
Some URIs refer to a location within a resource. This kind of URI ends with a "number sign" (#) followed by an anchor identifier (called the fragment identifier).
URIs with fragment identifiers link to a certain element within the document, known as the target element. For instance, here is a URI pointing to an anchor named section_2 in an HTML document:
http://example.com/html/top.html#section_2
A target element can be represented by the :target pseudo-class. If the document's URI has no fragment identifier, then the document has no target element.
https://www.w3.org/TR/selectors/#target-pseudo
当文档加载并且根据以下算法没有有效的 name
或 id
属性时,文档没有有效的片段标识符。
5.6.9 Navigating to a fragment identifier
...
- If there is an element in the DOM that has an ID exactly equal to decoded fragid, then the first such element in tree order is the indicated part of the document; stop the algorithm here.
- No decoded fragid: If there is an a element in the DOM that has a name attribute whose value is exactly equal to fragid (not decoded fragid), then the first such element in tree order is the indicated part of the document; stop the algorithm here.
https://www.w3.org/TR/html5/browsers.html#scroll-to-fragid
但是,似乎未指定供应商应如何处理具有等于 URL 片段的 id
或 name
属性的插入节点(这将在加载/导航文档时生成有效的片段标识符)。
关于html - :target selector on dynamic generated element not affect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37239084/