Shi*_*ibu 4 html javascript svg dom
//尝试从下面的 HTML 中检索 HTML 元素并尝试使用下面的 Javascript 代码单击它
<html>
<svg width="300" height="200">
<polygon points="100,10 40,198 190,78 10,78 160,198"
style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;" />
</svg>
</html>
<script>
var polygons = document.getElementsByTagName('polygon');
if(polygons.length>0)
{
//This statement doesn't work. Trying to simulate the click on the polygon element. The click function doesn't click it
polygons[0].click();
}
</script>
Run Code Online (Sandbox Code Playgroud)
与我的同伴相反,我会故意无视您没有设置点击事件侦听器的事实,而是回答每个人在这里错过的问题。
在click您要使用的方法是HTMLElement.click方法。
此方法可用于从 HTMLElement 继承的所有元素,但您<polygon>的 SVGPolygonElement 不是从 HTMLElement 继承的。
所以不,你不能在这个元素上使用这个方法,因为它的原型链中没有定义这样的方法。
// an SVGElement
var poly = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
// an HTMLElement
var unknown = document.createElement('foo');
console.log('<polygon> (SVG element)');
console.log('has click method:', !!poly.click);
console.log('inherits from HTMLElement:', poly instanceof HTMLElement);
console.log('//////////////////');
console.log('<foo> (HTML element)');
console.log('has click method:', !!unknown.click);
console.log('inherits from HTMLElement:', unknown instanceof HTMLElement);Run Code Online (Sandbox Code Playgroud)
但即使此方法不可用,您也可以很好地以编程方式触发单击事件,例如使用EventTarget.dispatchEvent方法。
var poly = document.getElementById('poly');
poly.dispatchEvent(new Event('click'));
function _log(evt) {
console.log('clicked');
}Run Code Online (Sandbox Code Playgroud)
<svg>
<polygon id="poly" points="60,20 100,40 100,80 60,100 20,80 20,40" onclick="_log()"/>
</svg>Run Code Online (Sandbox Code Playgroud)
或者由于您的问题似乎与 WPT 相关(我真的不知道),您似乎也可以使用该sendClick方法执行相同的操作,但是再一次,我不知道 WPT,我只是从快速阅读文档。
| 归档时间: |
|
| 查看次数: |
1939 次 |
| 最近记录: |