我有一些 JavaScript 在当前版本的 Chrome 上运行良好,但不适用于 Firefox。 Firefox 中悬停和单击的事件触发器失败,我认为这是影子 DOM 问题。
我可以用 JavaScript 悬停代码替换 CSS,它确实适用于 Firefox(不适用于 Chrome),但这无法解决点击事件的问题。
这里如何实现跨浏览器兼容性?
let elementsArray = document.querySelectorAll(".icon");
elementsArray.forEach(function(elem) {
console.log("getting element -"+String(elem));
elem.addEventListener("mouseenter", function() {
elem.setAttribute("style", " filter: grayscale(100%);");
});
elem.addEventListener("mouseout", function() {
elem.setAttribute("style", "");
});
elem.addEventListener("click", function() {
let hex = this.getAttribute('id');
console.log(hex);
});
});
<svg
width="600"
height="100"
>
<g id="layer0" class="slide" >
<path class="icon" id="y2011_0" d="M 285.0,45.0 300.0,70.98076211353316 285.0,96.96152422706632 255.0,96.96152422706632 240.0,70.98076211353316 255.0,45.0 z" fill="rgba(124,38,10,0.500000)"/>
<path class="icon" id="y2011_1" d="M 330.0,19.019237886466843 345.0,45.0 330.0,70.98076211353316 300.0,70.98076211353316 285.0,45.0 300.0,19.019237886466843 z" fill="rgba(124,39,10,0.500000)"/>
</g>
<use id="use" xlink:href="#layer0" href="#layer0" />
</svg>
最佳答案
如果动态创建 SVG
,代码会少很多,控制也会多
具有 W3C 标准Web 组件(所有现代浏览器都支持 JSWC)
<style>
svg { background: pink }
path { stroke: blue }
</style>
<game-board>
<hexagon x="46" y="0" />
<hexagon x="138" y="0" />
<hexagon x="92" y="26" />
<hexagon x="138" y="52" />
<hexagon x="92" y="78" />
<hexagon x="184" y="26" />
</game-board>
<script>
customElements.define("game-board", class extends HTMLElement {
connectedCallback() {
setTimeout(() => {
let svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.innerHTML = `<style>` +
`.hexagon{fill:red}.hexagon:hover{filter:grayscale(100%);cursor:pointer}` +
`.hexclicked{fill:green}` +
`</style>`;
svg.append(...[...this.querySelectorAll("hexagon")].map(hex => {
let path = document.createElementNS("http://www.w3.org/2000/svg", "path");
path.setAttribute("d", `m${hex.attributes.x.value} ${hex.attributes.y.value} 15 26-15 26-30 0-15-26 15-26z`);
path.classList.add("hexagon");
path.onclick = (evt) => path.classList.toggle("hexclicked");
return path;
}));
this.replaceWith(svg);
})
}
})
</script>
<hexagon>
是一个未知元素;保存以供使用,
请参阅:https://dev.to/dannyengelman/web-components-using-unknownhtmlelements-for-better-semantic-html-5d8c
关于javascript - Firefox:shadow-DOM 兼容性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68627996/