gpt4 book ai didi

javascript - Shadow DOM v1 - 在 lightroom 中输入文本更改

转载 作者:太空宇宙 更新时间:2023-11-04 15:47:56 29 4
gpt4 key购买 nike

我正在尝试监听自定义组件中的文本更改

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src="component.js"></script>
</head>
<body>
<fancy-p>
<p>Bar</p>
<!-- the input should be listened to -->
<input id="foo" type="text" name="text" placeholder="Hello"></input>
</fancy-p>
</body>
</html>

组件.js

customElements.define('fancy-p', class extends HTMLElement {
constructor() {
super();
this.attachShadow({mode: 'open'});
}
get foo() {
return "foo"
}
connectedCallback() {
this.shadowRoot.innerHTML = `
<style>
p {
color: red;
}
:host {
background-color: blue;
}
</style>
<div data-foo="bar">
<slot></slot>
</div>
`;

let input = this.querySelector("input");
console.log("input is:" + input);
}
});

我尝试监听文本更改并使用 querySelectorconnectedCallback但在 Chrome 70.xx 中,选择器返回 null .

似乎当我设置断点时 lightDOM 未填充(即插槽),但我不知道如何向输入添加事件监听器。

我该怎么做???

最佳答案

在您的示例中,<input>被放入 <slot>这意味着自定义元素之外的代码拥有 <input>标签。

在下面的代码中,您会看到我正在使用 document.querySelector在自定义元素之外获取 <input>元素而不使用 this.querySelectorthis.shadowRoot.querySelector在自定义元素代码中。

customElements.define('fancy-p', class extends HTMLElement {
constructor() {
super();
this.attachShadow({mode: 'open'});
}
get foo() {
return "foo"
}
connectedCallback() {
this.shadowRoot.innerHTML = `
<style>
p {
color: red;
}
:host {
background-color: blue;
}
</style>
<div data-foo="bar">
<slot></slot>
</div>
`;
let input = this.shadowRoot.querySelector("input");
console.log('inside input=',input); // input will be null
}
});


//Since the `<input>` tag is *owned* by the outside DOM you need to get the events from the outside:


let input = document.querySelector("input");
console.log('outside input=', input);
input.addEventListener('input', () => {
console.log("input is:" + input.value);
});
<fancy-p>
<p>Bar</p>
<input id="foo" type="text" name="text" placeholder="Hello"/></fancy-p>

如果你想通过 shadowDOM 访问它,那么你需要在 shadowDOM 中定义它:

customElements.define('fancy-p', class extends HTMLElement {
constructor() {
super();
this.attachShadow({mode: 'open'});
}
get foo() {
return "foo"
}
connectedCallback() {
this.shadowRoot.innerHTML = `
<style>
p {
color: red;
}
:host {
background-color: blue;
}
</style>
<div data-foo="bar">
<slot></slot>
<input id="foo" type="text" name="text" placeholder="Hello">
</div>
`;

let input = this.shadowRoot.querySelector("input");
console.log('inside input=',input);
input.addEventListener('input', () => {
console.log("input is:" + input.value);
});
}
});
<fancy-p>
<p>Bar</p>
</fancy-p>

关于javascript - Shadow DOM v1 - 在 lightroom 中输入文本更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53382342/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com