简体   繁体   English

选择具有JavaScript和/或CSS的Shadow DOM?

[英]Select Shadow DOM with JavaScript and/or CSS?

It seems like Chrome deprecated /deep/ and >>> and ::shadow : https://www.chromestatus.com/features/6750456638341120 似乎Chrome已弃用/deep/>>>::shadowhttps : //www.chromestatus.com/features/6750456638341120

Does anyone know if there is another way to access the Shadow DOM? 有谁知道是否还有另一种访问Shadow DOM的方法?

My use case is trying to figure out the style of an input. 我的用例试图弄清楚输入的样式。 Specifically I'm trying to detect if a placeholder is being displayed or not. 具体来说,我正在尝试检测是否正在显示占位符。

I've tried el.shadowRoot but it returns null and the docs for it are pretty sparse. 我试过el.shadowRoot但是它返回null,并且它的文档相当稀疏。

You can only access Shadow DOM of the elements created via a call to attachShadow( { mode: 'open' } ) . 您只能访问通过调用attachShadow( { mode: 'open' } )创建的元素的Shadow DOM。 If it is the case then calling shadowRoot should work. 如果是这种情况,则应调用shadowRoot

You cannot access Shadow DOM from user agent controls ( <input> , <select> ), added by the browser. 您无法从浏览器添加的用户代理控件( <input><select> )访问Shadow DOM。

To check if a placeholder is displayed or not, I would verify if it exists and if the input value is empty or not: 要检查是否显示占位符,我将验证它是否存在以及输入值是否为空:

if ( myInput.getAttribute( "placeholder" ) && !myInput.value.length )
    //the placeholder is being displayed

 myInput.oninput = function() { if (myInput.getAttribute("placeholder") && !myInput.value.length) myInput.classList.add("empty") else myInput.classList.remove("empty") } 
  body { padding: 100px; } input { border: 2px solid; padding: 10px; outline: none; } input:valid { border-color: springgreen; } input:invalid { border-color: tomato; } input[placeholder].empty { border-color: darkturquoise } 
 <input type="text" required placeholder="the placeholder" id="myInput" class="empty"> 

Update 更新

Chrome and Safari support the CSS pseudo-class :placeholder-shown that can be used to style your element when the placeholder is displayed. Chrome和Safari支持CSS伪类:placeholder-shown ,可在显示占位符时对元素进行样式设置。

If you use shady DOM (default) instead of shadow DOM, then you need to use Polymer API to access the DOM. 如果使用阴影DOM(默认值)而不是阴影DOM,则需要使用Polymer API来访问DOM。

Polymer.dom(el.root)

AFAIK it's not decided yet if >>> and ::shadow will be removed from JS. AFAIK尚未决定是否将>>>::shadow从JS中删除。 Therefore querySelector('x >>> y') might be supported longer. 因此,可能会更长地支持querySelector('x >>> y') For CSS it's definitive that it will be removed. 对于CSS,将其删除是绝对的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM