javascript - :target css selector not working in polymer

标签 javascript css polymer

我正在使用 Polymer,我注意到 :target CSS 选择器不起作用。

例如

<polymer-element name="my-element" noscript>
    <template>
        <style>
            :target {
                border: 2px solid red;
            }
        </style>
        <div id="test">This is a :target test</div>
    </template>
</polymer-element>

<a href="#test">Click me</a>
<my-element></my-element>

DEMO

有什么建议可以解决这个问题吗?

最佳答案

我必须承认:我对 shadow DOM 不是很熟悉,对 Polymer 也绝对不熟悉,但我想告诉你我对此的看法,因为你的意图对我和这个 对于评论来说太长了。

你不能使用伪选择器 :target在影子主机内。


很遗憾,我无法在这些资源中找到明确的证据

但是一些提示...

Web Components 的目标是让我们能够构建单独和隔离的组件,这些组件可以在文档中使用,而无需关心它们的内部功能或样式。

如果一个组件可以直接访问“外部”文档,或者如果外部文档可以直接访问任何影子主机元素,这将完全破坏 Web 组件的意图。

想象一下,如果您插入 <my-element> 的两个实例会发生什么? .两者都包含相同的 ID,应该定位哪一个?

当然可以到达影子文档,或者从影子文档中包含的文档,但只能通过::shadow。或 :host分别。

对我来说,浏览器不能仅使用 :target 选择元素是合乎逻辑的。选择器,因为目标是文档的问题(它的 URL 是针对某个 ID 的)而不是任何影子 DOM 的问题。也无法通过 document.getElementById() 到达影子树节点。来自容器文档

CSS scoping spec这也涉及 Shadow DOM 概念状态:

Why is the shadow host so weird?

The shadow host lives outside the shadow tree, and its markup is in control of the page author, not the component author.

It would not be very good if a component used a particular class name internally in a shadow tree, and the page author using the component accidentally also used the the same class name and put it on the host element. Such a situation would result in accidental styling that is impossible for the component author to predict, and confusing for the page author to debug.

( 3.1.1. Host Elements in a Shadow Tree )

我想说这是另一个证据:影子主机(从外部看)本身将保持事件(焦点)状态,同时处理其树内的焦点。

To maintain encapsulation, the value of the Document object's focus API property activeElement must be adjusted. To prevent loss of information when adjusting this value, each shadow root must also have an activeElement property to store the value of the focused element in the shadow tree.

( 6.3 Active Element )


一种可能的解决方案

如果您只想突出显示 div , 当你的影子元素是 :target ed 这可能是影子文档中的正确样式:

<polymer-element name="my-element" constructor="" attributes="">
  <template>
     <style>
         :host(:target) #inner {
             color: #0c0;
         }
     </style>
     <content>Hello World!</content>
     <div id="inner">This is a :target test</div>
...

它将突出显示 <div>带有绿色文本,当你的影子元素 <my-element id="outer"></my-element> #outer 的目标.

如果这不是您的本意,并且您真的希望能够定位 #inner从外部来看,我会说这是不可能的(请参阅“较长”部分;)。

关于javascript - :target css selector not working in polymer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27671567/

相关文章:

css - Bootstrap 导航选项卡/药丸仅在第一次交互时有效

polymer - dom-repeat 模板无法呈现数组,错误为 'expected array for items'

css - 更改 polymer 中 gold-email-input 的大小

javascript - 将 Javascript 命令外壳集成到 Web 浏览器中?

javascript - 某些 JavaScript 不会在 WordPress 上加载

javascript - 测试 HTML 属性是否存在并获取值

jquery - 相对父项中的绝对元素 - 不与其他父项重叠

javascript - 使用 javascript 显示隐藏的 HTML 元素

html - 单选按钮的样式

javascript - 如何使用 ajax-core + Polymer 发出 JsonP 请求