以下是我檢測 SVG 行點擊的方法:
window.onmousedown = (e) => {
if (e.target.tagName == 'line') {
alert(); // do something with e.target
}
}
svg line:hover { cursor: pointer; }
<svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" id="svg">
<line x1="320" y1="160" x2="140" y2="00" stroke="black" stroke-width="2"></line>
<line x1="140" y1="00" x2="180" y2="360" stroke="black" stroke-width="2"></line>
<line x1="180" y1="360" x2="400" y2="260" stroke="black" stroke-width="2"></line>
<line x1="00" y1="140" x2="280" y2="60" stroke="black" stroke-width="2"></line>
</svg>
它只有在滑鼠游標精確在線時才有效,這并不容易,所以這是一個糟糕的用戶體驗。
如何從 Javascript 中檢測對 SVG 線的點擊,即使不是完全在線,但距離 <= 3 像素?
uj5u.com熱心網友回復:
有點棘手的解決方案,但可以完成作業:
window.onmousedown = (e) => {
if (e.target.classList.contains('line')) {
console.log(e.target.href);
}
}
svg .line:hover {
cursor: pointer;
}
.line {
stroke: black;
stroke-width: 2px;
}
.line.stroke {
stroke: transparent;
stroke-width: 6px;
}
<svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" id="svg">
<defs>
<line id="line1" x1="320" y1="160" x2="140" y2="00"></line>
<line id="line2" x1="140" y1="00" x2="180" y2="360"></line>
<line id="line3" x1="180" y1="360" x2="400" y2="260"></line>
<line id="line4" x1="00" y1="140" x2="280" y2="60"></line>
</defs>
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#line1" class="line stroke"></use>
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#line1" class="line"></use>
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#line2" class="line stroke"></use>
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#line2" class="line"></use>
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#line3" class="line stroke"></use>
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#line3" class="line"></use>
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#line4" class="line stroke"></use>
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#line4" class="line"></use>
</svg>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/454212.html
標籤:javascript svg 徘徊 老鼠