![](/img/trans.png)
[英]JavaScript and SVG: how do you increase the clickable area for an onClick event?
[英]How to make an inline svg clickable in html/css to use onclick in javascript?
我的 html 中有一个内联 svg:
<svg id="nav-search-icon" xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32.2 32.2"><path d="M19 0C11.8 0 6 5.8 6 13c0 3.1 1.1 5.9 2.9 8.2l-8.6 8.6c-0.5 0.5-0.5 1.4 0 2 0.5 0.5 1.4 0.5 2 0l8.6-8.6C13.1 24.9 15.9 26 19 26c7.2 0 13-5.8 13-13S26.2 0 19 0zM19 24C12.9 24 8 19.1 8 13S12.9 2 19 2 30 6.9 30 13 25.1 24 19 24z"/></svg>
我想让另一个元素在单击 svg 时可见或隐藏。 这是我用来执行此操作的 javascript:
let searchIcon = document.querySelector('#nav-search-icon')
let searchBar = document.querySelector('#search-bar')
searchIcon.onclick = function() {
if (searchBar.style.visibility === 'hidden') {
searchBar.style.visibility = 'visible'
} else if (searchBar.style.visibility === 'visible') {
searchBar.style.visibility = 'hidden'
}
}
javascript 代码不起作用。 我认为它不起作用的原因是 svg 元素不可点击(我的鼠标图标在悬停在 svg 上时不会从指针变为手)。 我试着将pointer-events="all"
的svg
元素,也给path
里面元素svg
元素。 我也试过添加pointer-events: all;
到 CSS。 这些都没有奏效。
**编辑:** 我查看了有关使 svg 链接可点击的问题(通过在 svg 元素外添加<a>
标签)。 我不想链接到另一个页面。 我想让 onclick 为 svg 元素工作。
我对JS
进行了一些更改,但将SVG
包裹在<a>
标签内并添加了onclick()
,如下所示:
searchClick = function() { let searchIcon = document.querySelector('#nav-search-icon') let searchBar = document.querySelector('#search-bar') if (searchBar.style.display === 'none') { searchBar.style.display = 'block' } else { searchBar.style.display = 'none' } }
<a href="#" onclick="searchClick();"><svg id="nav-search-icon" xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32.2 32.2"><path d="M19 0C11.8 0 6 5.8 6 13c0 3.1 1.1 5.9 2.9 8.2l-8.6 8.6c-0.5 0.5-0.5 1.4 0 2 0.5 0.5 1.4 0.5 2 0l8.6-8.6C13.1 24.9 15.9 26 19 26c7.2 0 13-5.8 13-13S26.2 0 19 0zM19 24C12.9 24 8 19.1 8 13S12.9 2 19 2 30 6.9 30 13 25.1 24 19 24z"/></svg></a> <div style="display: none;" id="search-bar"> <input width="200" value="Search"/> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.