我在SVG教程中找到了这个示例,该教程解释了如何为SVG元素使用onclick事件处理程序。看起来像下面的代码:
<svg xmlns='http://www.w3.org/2000/svg' version='1.1' height='600' width='820'>
<script type="text/ecmascript"><![CDATA[
function changerect(evt)
{
var svgobj=evt.target;
svgstyle = svgobj.getStyle();
svgstyle.setProperty ('opacity', 0.3);
svgobj.setAttribute ('x', 300);
}
]]>
</script>
<rect onclick='changerect(evt)' style='fill:blue;opacity:1' x='10' y='30' width='100'
height='100' />
</svg>
然而,这似乎不起作用。当我单击该元素时,没有任何反应。
也许值得一提的是,我使用echo从PHP脚本内部显示SVG。还要注意,PHP脚本生成的内容是使用AJAX和XMLHttpRequest()引入页面的。
这可能与此有关吗?非常感谢你的帮助。
发布于 2013-05-10 07:27:54
似乎所有的JavaScript都必须包含在SVG中才能运行。我无法引用任何外部函数或库。这意味着您的代码在svgstyle = svgobj.getStyle();处崩溃了
这将完成您正在尝试的操作。
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns='http://www.w3.org/2000/svg' version='1.1' height='600' width='820'>
<script type="text/ecmascript"><![CDATA[
function changerect(evt) {
var svgobj=evt.target;
svgobj.style.opacity= 0.3;
svgobj.setAttribute ('x', 300);
}
]]>
</script>
<rect onclick='changerect(evt)' style='fill:blue;opacity:1' x='10' y='30' width='100'height='100' />
</svg>
发布于 2014-03-31 15:26:24
Demo in JSFiddle
var _reg = 100;
var _l = 10;
// Create PATH element
for (var x = 1; x < 20; x++) {
var pathEl = document.createElementNS("http://www.w3.org/2000/svg", "path");
pathEl.setAttribute('d', 'M' + _l + ' 100 Q 100 300 ' + _l + ' 500');
pathEl.style.stroke = 'rgb(' + (_reg) + ',0,0)';
pathEl.style.strokeWidth = '5';
pathEl.style.fill = 'none';
$(pathEl).mousemove(function(evt) {
$(this).css({ "strokeWidth": "3", "stroke": "#ff7200" })
.hide(100).show(500).css({ "stroke": "#51c000" })
});
$('#mySvg').append(pathEl);
_l += 50;
}发布于 2017-05-12 23:45:21
如果您不需要单击svg的特定部分,这可能是一种可行的解决方案:
在顶部放置一个div,并向该div添加事件。如果svg元素在html结构中的div标签之前,则不需要z索引。
HTML
<div class='parent'>
<div class='parent-events'></div>
<div class='my-svg'><svg></svg></div>
</div>CSS
.parent {
position: relative;
}
.my-svg {
position: relative;
z-index: 0;
}
.parent-events {
position: absolute;
width: 100%;
height: 100%;
z-index: 1
}Javascript
const eventArea = document.querySelector('.parent-events');
eventArea.addEventListeners('click', () => {
console.log('clicked');
});https://stackoverflow.com/questions/16472224
复制相似问题