在获得成功加载事件后,我无法点击 svg。有什么线索吗?我正在控制台记录返回的 SVG 对象,但我没有获得任何点击操作。
https://jsfiddle.net/tz2knqhr/
<embed src="https://www.okcode.pl/img/bg-square.svg" id="embed2" width="15%" height="auto" type="image/svg+xml"></embed>
<script>
function resolveAfter() {
return new Promise(function(resolve,reject){
window.addEventListener('load',function(){
let image = document.getElementById("embed2")
resolve(image);
})
});
}
async function asyncCall() {
console.log('calling');
const result = await resolveAfter();
console.log('result',result);
result.addEventListener('click',function(event){
console.log("clicked")
location.href = "http://google.com"
})
}
asyncCall();
</script>
最佳答案
您需要将您的 embed
包装在一个 object
中,以便它可以接收点击。为确保该对象始终接收到点击事件,我在 embed
调用后为其所有(最终)子对象设置了 pointer-events: none
。另请注意,点击事件设置在函数返回(对象
)的parentNode
上,而不是embed
。
function resolveAfter() {
return new Promise(function(resolve, reject) {
window.addEventListener('load', function() {
let image = document.getElementById("embed2")
resolve(image);
})
});
}
async function asyncCall() {
console.log('calling');
const result = await resolveAfter();
console.log('result', result.parentNode);
result.parentNode.addEventListener('click', function(event) {
console.log("made it");
// location.href = "http://google.com"
})
}
asyncCall();
* {
box-sizing: border-box;
}
html,
body {
height: 100vh;
width: 100vw;
padding: 0%;
margin: 0%;
background-color: white;
}
object {
display: inline-flex;
}
object * {
/* ignore clicks to children */
pointer-events: none;
}
object embed {
flex: 1;
}
<object style="width: 15%; height: auto;">
<embed src="https://www.okcode.pl/img/bg-square.svg" id="embed2" width="15%" height="auto" type="image/svg+xml" />
</object>
关于javascript - 调用成功后甚至无法点击 SVG 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60514171/