如何解决SVG 元素在单击或鼠标悬停时缩放整个 SVG 组
我想使用我的 SVG 文件中的圆圈来触发以圆圈为中心的放大。我已经使用 div 作为缩放触发器,但如果我改为将 id="pin" 应用于 SVG 中的一个圆元素,它不再放大。谁能告诉我这是为什么?>
是否有更好的方法来实现我的目标?理想情况下,我希望可以单击放大,然后在放大时访问 SVG 中的其他交互性。 如果这是不可能的,是否有一种简单的方法来缩放和平移 SVG 并能够在缩放时访问 SVG 交互性?
如果我错过了一些明显的东西,请原谅我,我还在学习基础知识!
粗略的例子: CodePen link
<div id="pin">click to trigger zoom</div>
<div class="map" id="mapFrame">
<svg class="image" id="mapsvg" version="1.1" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 1920 1442.5"" style="
enable-background:new 0 0 1920 924.9;" xml:space="preserve">
<g id="Layer_7" data-name="Layer 7">
<image width="1800" height="1350" transform="translate(0) scale(1.069)" opacity="0.3"
xlink:href="https://media.npr.org/assets/img/2020/07/04/seamus-coronavirus-d3-world-map-20200323_wide-a3888a851b91a905e9ad054ea03e177e23620015.png" />
</g>
<g id="one">
<circle cx="929.664" cy="944.287" r="81.191"/>
</g>
<g id="two">
<circle cx="638.164" cy="456.863" r="81.191" />
</g>
<g id="three">
<circle cx="1266.164" cy="498.868" r="81.191" />
</g>
</svg>
</div>
<script src="app.js"></script>
svg {
width: 100%;
height: auto;
}
#pin {
position: absolute;
height: 65px;
width: 75px;
top: 300px;
left: 550px;
padding: 10px;
background-color: yellow;
}
let imgElement = document.querySelector('#mapFrame');
let pinElement = document.querySelector('#pin');
pinElement.addEventListener('click',function (e) {
imgElement.style.transform = 'translate(-' + 0 + 'px,-' + 0 + 'px) scale(2)';
pinElement.style.display = 'none';
});
imgElement.addEventListener('click',function (e) {
imgElement.style.transform = null;
pinElement.style.display = 'block';
});
解决方法
当您点击圆圈时,您同时也点击了背景图片,从而触发了两个事件,这实质上是取消缩放。如果将 alert('click 1');
和 alert('click 2');
放在侦听器中,您可以看到这一点。
这不会发生在 #pin
元素上,因为它在背景 div 之外并避免了事件冒泡。这是通过添加 event.stopPropagation();
来自您的 CodePen 的代码:
let imgElement = document.querySelector('#mapFrame');
let pinElement = document.querySelector('#one'); //changed to #one
pinElement.addEventListener('click',function (e) {
imgElement.style.transform = 'translate(-' + 0 + 'px,-' + 0 + 'px) scale(2)';
pinElement.style.display = 'none';
event.stopPropagation(); //added to prevent bubbling
});
imgElement.addEventListener('click',function (e) {
imgElement.style.transform = null;
pinElement.style.display = 'block';
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。