如果我捕获了onclick事件以在SVG文档中缩放和平移,我如何到达锚点href

How do I reach an anchor href if I have trapped the onclick event to zoom and pan in an SVG document?

本文关键字:href onclick 事件 如果 文档 SVG 缩放      更新时间:2023-09-26

我有一个SVG文档,其中我使用javascript来实现缩放和平移功能[改编自Andrea Leofredi的SVGPan库]。SVG本身有一个锚点元素,它应该启动一个单独的url。我的问题是,由于onclick事件已被捕获以进行缩放和平移,因此无法访问锚点上的href。我怎样才能使锚与onclick trap绝缘?

在下面的代码中,当我点击文本"厨房水槽"时,我想启动附加到它的url,而不是进入缩放和平移模式:

代码片段:

SVGLib.js:

...
setupHandlers(root);
function setupHandlers(root){
    setAttributes(root, {
        "onclick" : "handleClick(evt)"
    });
        root.addEventListener('DOMMouseScroll', handleMouseWheel, false); 
}

function handleClick(evt) {
    if(evt.preventDefault)
        evt.preventDefault();
    evt.returnValue = false;
    var svgDoc = evt.target.ownerDocument;
    var g = getRoot(svgDoc);
        // Get the click location
        // If key button clicked with shift key down, reset
        if (evt.shiftKey == 1) {
                setCTM(g, root.createSVGMatrix());
                shiftX = initShiftX;
                shiftY = initShiftY;
        }
        else {
                var ctm = g.getCTM();
                var ctmInv = ctm.inverse();
                var newctm = g.getCTM();
                // showMatrix('before: ', newctm);
                shiftX = shiftX - (evt.clientX - initShiftX);
                shiftY = shiftY - (evt.clientY - initShiftY);
                newctm.e = shiftX * vbCTMInv.a;
                newctm.f = shiftY * vbCTMInv.d;
                // bring in the scale factors from the vbCTMInv -- because scaling will apply automatically via the vb transform
                newctm.a = newctm.a*vbCTMInv.a;
                newctm.d = newctm.d*vbCTMInv.d;
                // showMatrix('after: ', newctm);
                setCTM(g, newctm);
        }
}

doc.html:

<html>
...
<svg>
...
        <g id="g33" style="fill: none; stroke: green">
            <a xlink:href="/cgi-bin/qbui/drive.pl?sqlHandle=693F1DB6-6C7F-11E1-8475-31DDD99CA768">
                <text id="t2769800058" style="text-anchor: middle; font-family: Verdana; font-size: 10px" x="600" y="1300">Kitchen Sink</text>
            </a>
        </g>
...
</svg>
</html>

更新:

我已经找到了一个可以用来检测事件目标并采取适当行动的方法。如果单击"Kitchen Sink",则id是SVG文本元素的id。当然,这需要对代码进行一些更改,但这是可行的。

在handleClick()中:

if (evt.target.id == ...)  {
...
}

您可以检查evt.target的href值是否有值,以及它是否跟随

function handleClick(evt) {
  if(evt.target.href){
    window.location = evt.target.href;
  }