html - :target selector on dynamic generated element not affect

标签 html css google-chrome css-selectors

我的测试表明,: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

当文档加载并且根据以下算法没有有效的 nameid 属性时,文档没有有效的片段标识符。

5.6.9 Navigating to a fragment identifier

...

  1. 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.
  2. 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 片段的 idname 属性的插入节点(这将在加载/导航文档时生成有效的片段标识符)。

关于html - :target selector on dynamic generated element not affect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37239084/

相关文章:

google-chrome - 是否可以在 Google Chrome 中禁用元刷新?

javascript - 表格单元格中的工具提示定位

html - [HTML][CSS] 包含另外 3 个 div 的 Div 不会居中

html - 将图像放置在具有响应宽度和高度的另一图像的中央

html - 表格在小设备宽度上溢出父级

android - 我认为适用于 Android 的谷歌浏览器有一个奇怪的视口(viewport)高度错误,应该修复它。目前,你如何处理它?

php - <select> 的值不在 <options> 中

javascript - IE9 是否按文档顺序加载 SVG dom?

html - 如何告诉谷歌我在不同域上有不同语言的网站

css - 检查包含 kendo-ui 样式的页面中的元素时,Google Chrome Devtools 崩溃