0

我想使用我的 SVG 文件中的圆圈来触发以圆圈为中心的放大。我已经使用 div 作为缩放的触发器,但是如果我将 id="pin" 应用于 SVG 中的一个圆形元素,它就不再放大了。谁能告诉我这是为什么?

有没有更好的方法来实现我想要做的事情?理想情况下,我希望能够单击以缩放,然后在放大时访问 SVG 中的其他交互性。如果这不可能,是否有一种简单的方法来缩放和平移 SVG 并能够访问 SVG 交互性放大时?

如果我遗漏了一些明显的东西,请原谅我,我还在学习基础知识!

粗略示例: CodePen 链接


    <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';
});
4

1 回答 1

1

When you click on the circle, you are also clicking on the background image as well, triggering two events which is essentially cancelling the zoom. You can see this if you place alert('click 1'); and alert('click 2'); in your listeners.

This doesn't happen on the #pin element because it's outside background div and avoids the event bubbling up. This is solved by adding event.stopPropagation();

Code from your 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';
});
于 2021-07-23T21:32:38.213 回答