我一直在阻止SVG中不需要的事件。簡而言之,在http://3lectronics.com/sof/prevDef.svg你可能會看到一個例子。嘗試點擊圓形並在矩形上畫線。徘徊時,它們變成白色。如何預防Javascript + SVG中發生的事件
事件正在解僱,我希望他們死亡! 請告訴我如何在繪製線條時關閉其他元素上的事件。
SVG代碼
<svg id ="svgRoot" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" onload="load(evt)" >
<script type="text/ecmascript" xlink:href="prevDef.js"/>
<rect x="0" y="0" width="100%" height="100%" fill="#009399"/>
<rect id="R" x="150" y="150" width="200" height="30" fill="khaki" onmouseover="this.setAttribute('fill', 'white')" onmouseout="this.setAttribute('fill', 'khaki')"/>
<circle cx="250" cy="75" r="50" fill="blue" onclick="drawLine(evt)"/>
</svg>
JS代碼
var newL;
var xmlns="http://www.w3.org/2000/svg";
var cont=document.getElementById("svgRoot");
function load(evt) {
var rect=document.getElementById("R");
var offset=40;
for (var i=1;i<7;i++) {
var newR=rect.cloneNode(true);
newR.setAttributeNS(null, "y", 150+i*offset);
cont.appendChild(newR);
}
}
function drawLine(evt) {
if (window.svgDocument == null) svgDocument=evt.target.ownerDocument;
newL=svgDocument.createElementNS(xmlns, "line");
newL.setAttributeNS(null, "stroke", "black");
newL.setAttributeNS(null, "x1", evt.clientX);
newL.setAttributeNS(null, "y1", evt.clientY);
newL.setAttributeNS(null, "x2", evt.clientX);
newL.setAttributeNS(null, "y2", evt.clientY);
newL.setAttributeNS(null, "stroke-width", "1");
cont.appendChild(newL);
cont.setAttributeNS(null, "onmousemove", "moveLinPt(evt)");
}
function moveLinPt(evt) {
newL.setAttributeNS(null, "x2", evt.clientX);
newL.setAttributeNS(null, "y2", evt.clientY);
cont.setAttributeNS(null, "onclick", "moveLinEnd()");
}
function moveLinEnd() {
cont.setAttributeNS(null, "onmousemove", null);
cont.setAttributeNS(null, "onclick", null);
}
但是,嘗試上面的鏈接。
爲什麼不直接刪除事件偵聽器你不感興趣?無關的問題:爲什麼你設置「onclick」等等而不是使用Element.addEventListener(...)? –
嗯,我認爲這是將事件監聽器添加到標記的「正確」方式,並且不想冒險。謝天謝地,你告訴我不要成爲SVG標記的奴隸,我想到了。 如果我說得對,你建議我管理所有事件programmaticaly?感謝這裏(都)。 – Alex