当光标进入svg圆圈时,我试图应用svg掩码。掩蔽正常工作,但事件不会触发。
如何正确地将事件侦听器设置为svg元素,以便当<svg id="container">中包含的圆圈悬空时,掩码被应用于<rect id="masked">
const svg = document.getElementById('container')
svg.addEventListener('onmouseover', (e) => {
console.log('hover')
const masked = document.getElementById('masked')
masked.setAttribute('fill', 'grey')
masked.setAttribute('fill-opacity', '70%')
masked.setAttribute('mask', 'url(#myMask)')
})
svg.addEventListener('onmouseleave', (e) => {
console.log('leave')
const masked = document.getElementById('masked')
masked.setAttribute('fill', 'none')
masked.setAttribute('fill-opacity', '100%')
masked.removeAttribute('mask')
})html,
body {
margin: 0;
width: 100%;
height: 100%;
background-color: yellow;
}
svg,
circle {
pointer-events: all;
}<svg id="mySVG" width="600" height="250">
<mask id="myMask" x="0" y="0" width="600" height="250">
<rect width="400" height="250" fill="white" />
<circle cx="25" cy="25" r="25" fill="black" />
</mask>
<rect id="masked" x="0" y="0" width="600" height="250" fill="grey"></rect>
<!-- The following svg element is supposed to trigger events -->
<svg id="container">
<!-- This circle overlaps the circle in <mask> -->
<circle cx="25" cy="25" r="25" fill="none" stroke="black" />
</svg>
</svg>
发布于 2022-09-06 10:41:32
这些事件被称为mouseover和mouseleave,而不是onmouseover和onmouseleave。
const svg = document.getElementById('container')
svg.addEventListener('mouseover', (e) => {
console.log('hover')
const masked = document.getElementById('masked')
masked.setAttribute('fill', 'grey')
masked.setAttribute('fill-opacity', '70%')
masked.setAttribute('mask', 'url(#myMask)')
})
svg.addEventListener('mouseleave', (e) => {
console.log('leave')
const masked = document.getElementById('masked')
masked.setAttribute('fill', 'none')
masked.setAttribute('fill-opacity', '100%')
masked.removeAttribute('mask')
})html,
body {
margin: 0;
width: 100%;
height: 100%;
background-color: yellow;
}
svg,
circle {
pointer-events: all;
}<svg id="mySVG" width="600" height="250">
<mask id="myMask" x="0" y="0" width="600" height="250">
<rect width="400" height="250" fill="white" />
<circle cx="25" cy="25" r="25" fill="black" />
</mask>
<rect id="masked" x="0" y="0" width="600" height="250" fill="grey"></rect>
<!-- The following svg element is supposed to trigger events -->
<svg id="container">
<!-- This circle overlaps the circle in <mask> -->
<circle cx="25" cy="25" r="25" fill="none" stroke="black" />
</svg>
</svg>
https://stackoverflow.com/questions/73612550
复制相似问题