2012-02-02 137 views
6

我的脚本在笔画宽度为3时在屏幕上绘制线条。线条的大小是理想的(直观),但它们不是很容易点击。JavaScript和SVG:如何增加onClick事件的可点击区域?

作一个粗略的例子:

<html> 
<head> 
<script> 
function selectStrand(evt) { 
    current_id = evt.target.getAttributeNS(null, "id"); 

    document.getElementById('main').innerHTML = current_id; 
} 
</script> 
</head> 

<body> 
Selected line: <span id="main"></span> 

<?xml version="1.0"?> 
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%" preserveAspectRatio="xMinYMin meet" viewBox="0 0 1000 1000"> 
    <g id="buffer" transform="translate(10,0)"> 
     <line id="blue-blue" x1="50" y1="50" x2="500" y2="50" style="stroke:blue; stroke-width: 4;" stroke-linecap="round" onclick="selectStrand(evt)"/> 
     <line id="blue-orange" x1="50" y1="70" x2="500" y2="70" style="stroke:orange; stroke-width: 4;" stroke-linecap="round" onclick="selectStrand(evt)"/> 
     <line id="blue-green" x1="50" y1="90" x2="500" y2="90" style="stroke:green; stroke-width: 4;" stroke-linecap="round" onclick="selectStrand(evt)"/> 
     <line id="blue-brown" x1="50" y1="110" x2="500" y2="110" style="stroke:brown; stroke-width: 4;" stroke-linecap="round" onclick="selectStrand(evt)"/> 
     <line id="blue-grey" x1="50" y1="130" x2="500" y2="130" style="stroke:grey; stroke-width: 4;" stroke-linecap="round" onclick="selectStrand(evt)"/> 
     <line id="blue-khaki" x1="50" y1="150" x2="500" y2="150" style="stroke:khaki; stroke-width: 4;" stroke-linecap="round" onclick="selectStrand(evt)"/> 
     <line id="blue-red" x1="50" y1="170" x2="500" y2="170" style="stroke:red; stroke-width: 4;" stroke-linecap="round" onclick="selectStrand(evt)"/> 
     <line id="blue-black" x1="50" y1="190" x2="500" y2="190" style="stroke:black; stroke-width: 4;" stroke-linecap="round" onclick="selectStrand(evt)"/> 
     <line id="blue-yellow" x1="50" y1="210" x2="500" y2="210" style="stroke:yellow; stroke-width: 4;" stroke-linecap="round" onclick="selectStrand(evt)"/> 
     <line id="blue-purple" x1="50" y1="230" x2="500" y2="230" style="stroke:purple; stroke-width: 4;" stroke-linecap="round" onclick="selectStrand(evt)"/> 
     <line id="blue-pink" x1="50" y1="250" x2="500" y2="250" style="stroke:pink; stroke-width: 4;" stroke-linecap="round" onclick="selectStrand(evt)"/> 
     <line id="blue-cyan" x1="50" y1="270" x2="500" y2="270" style="stroke:cyan; stroke-width: 4;" stroke-linecap="round" onclick="selectStrand(evt)"/> 
    </g> 
    </g> 
</svg> 

</body> 
</html> 

有没有一种简单的方法,以增加周围每一行的区域,使它们更容易点击?

回答

8

对于每一行,尝试在它的顶部绘制一个具有较大笔画宽度的透明线,并在其上设置onclick。

+0

好,很好,谢谢。这有效,似乎是最好的方法。 – renosis 2012-02-02 18:19:04

+4

您可能希望在您的示例中将click事件侦听器添加到根或id = buffer的组中,并查看您得到的事件的目标以确定哪个线路被点击。这样你只需要一个事件监听器,而不是每个元素上的一个。 呵呵,''部分是不必要的,当在html中包含svg内联时,它将被忽略。 – 2012-02-03 09:09:00

+0

很酷,谢谢Erik! – renosis 2012-02-06 13:10:26

0

上述答案的变体。对于一个很酷的选择效果组,每条细线和透明线组合在一起,细线在上面。将onclick设置为该组,然后在onclick中为粗线的透明度设置动画效果。

+0

雅,当我想出整体机制时,我正在考虑用onClick做点华丽的事情......听起来像个好主意。谢谢你的提示! – renosis 2012-02-06 13:11:59