简体   繁体   English

隐藏和显示 shadow dom 中的元素

[英]Hide and Show elements inside shadow dom

Im trying to create a search bar type filter within shadow dom as follows我试图在 shadow dom 中创建一个搜索栏类型过滤器,如下所示

const root =  mainContainer.attachShadow({ mode: "open" });

      var filter = root.getElementById("myInput"), // search box
          list = root.querySelectorAll(".clubguests-card"); // all list items
          
     
      // (B) ATTACH KEY UP LISTENER TO SEARCH BOX
      filter.onkeyup = () => {
        // (B1) GET CURRENT SEARCH TERM
        let search = filter.value.toLowerCase();
     
        // (B2) LOOP THROUGH LIST ITEMS - ONLY SHOW THOSE THAT MATCH SEARCH
        for (let i of list) {
        
          let item = i.className.toLowerCase();
          console.log(item);
          if (item.indexOf(search) == -1) { i.classList.add("hide"); }
          else { i.classList.remove("hide"); }
        }
    }

The console is showing that the classes are added/removed, but the display is not affected.控制台显示类已添加/删除,但显示不受影响。

If I use document.querySelectorAll(".clubguests-card") it works fine.如果我使用 document.querySelectorAll(".clubguests-card") 它工作正常。

IS there a way of making this work within the shadow dom?有没有办法在 shadow dom 中完成这项工作?

Because shadow dom elements are isolated from outside styling.因为 shadow dom 元素与外部样式隔离。

You can link a stylesheet or use the visbility property to show/hide your shadow elements.您可以链接样式表或使用可见性属性来显示/隐藏阴影元素。

Note that inherited properties can go through the shadow boundary.请注意, 继承的属性可以 go 通过阴影边界。

You can use the :host selector to access classes (and attributes) on the host/custom element;您可以使用:host选择器访问主机/自定义元素上的类(和属性);
then use CSS properties inside the component to set detailed styling然后在组件内部使用 CSS 属性来设置详细的样式

 <my-component></my-component> <my-component class="hide"></my-component> <my-component class="show"></my-component> <script> customElements.define("my-component",class extends HTMLElement{ constructor(){ super().attachShadow({mode:"open"}).innerHTML = ` <style>:host(.hide){ /* display:none; */ --bgcolor:red; }:host(.show){ --bgcolor:green; } h1{ background: var(--bgcolor,grey); } </style> <h1>Hello Web Component!</h1>` } }) </script>

Had you included a StackOverflow snippet in your question, I could have applied it to your source code.如果您在问题中包含StackOverflow 片段,我可以将其应用到您的源代码中。

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

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