Мое понимание вопроса заключается в том, что существуют различные аспекты, которые необходимо решить:
- Как подготовить изображение для взаимодействия
- Как вставить изображение на страницу
- Как использовать CSS с SVG
- Как использовать JavaScript для взаимодействия
Подготовка изображения
Прежде всего, я бы рекомендовал очистить изображение. Inkscape оставляет все, что вам не нужно, включая элементы и атрибуты в пространствах имен sodipodi:
и inkscape:
, а также повторяющийся и/или избыточный стиль атрибутов. У вас не есть , чтобы удалить это, но это экономит вам время загрузки/загрузки, а если вы хотите работать с совпадением CSS, то атрибуты стиля на вашем пути.
В вашем файле примера у вас есть 472-кратный один и тот же атрибут стиля. Удалите все из них и создайте эквивалентное правило CSS один раз.
Вы также можете добавить некоторую информацию о муниципалитетах к разметке. Вы можете, например, изменить идентификаторы каждого пути, представляющего муниципалитет, в соответствии с его названием. Для этой цели вы также можете использовать атрибут data - *
. Последнее имеет то преимущество, что вы можете использовать пробелы. См. Ниже, как это полезно для взаимодействия, особенно с CSS.
Вставка изображения
Я бы рекомендовал использовать SVG inline, особенно если вы хотите взаимодействовать с CSS/JavaScript. Это означает, что вы просто добавляете разметку SVG в свой HTML или загружаете и вставляете ее с помощью Ajax. Последнее имеет то преимущество, что окружающая страница загружается быстрее и чувствует себя более отзывчивой.
Пример встроенного элемента SVG:
<div id="svgContainer">
<!-- This is an HTML div, and inside goes the SVG -->
</div>
Упрощенный пример загрузки SVG с использованием Ajax:
xhr = new XMLHttpRequest();
xhr.open("GET","my.svg",false);
// Following line is just to be on the safe side;
// not needed if your server delivers SVG with cилиrect MIME type
xhr.overrideMimeType("image/svg+xml");
xhr.send("");
document.getElementById("svgContainer")
.appendChild(xhr.responseXML.documentElement);
Как использовать CSS
SVG можно создать так же, как HTML. Конечно, SVG имеет собственный набор свойств, таких как fill-opacity
или stroke-dasharray
и не поддерживает много свойств HTML, например margin
код>, позиция
или тому подобное. Но механизмы выбора на 100% одинаковы.
You can mix the CSS fили your inline SVG with the CSS fили your HTML, either inside a
element или an external CSS file. You can also use the
element inside the SVG code and style
attributes.
Предполагая, что вы предоставили свои идентификаторы SVG значимых идентификаторов или атрибутов data - *
, два способа выделения муниципалитетов с использованием CSS:
#Bronckhилиst, #Laarbeek {fill:red}
или
*[data-gemeente=Bronckhилиst], *[data-gemeente=Laarbeek] {fill:red}
или, of course, you can change the style attributes of the respective elements. Properties are also suppилиted as attribute, i.e. style="stroke-width:2"
can also be specified like stroke-width="2"
. If the same property is set using both an attribute and CSS (either using the style attribute, a style element или an external stylesheet), the CSS overrides the attribute.
взаимодействие с JavaScript
There is basically no difference between HTML and SVG regarding JavaScript interaction, at least as long as you use plain vanilla DOM. This means, HTML specific features like innerHTML
are not suppилиted in SVG (i.e. there is no innerSVG
). But SVG has its own graphics specific set of DOM methods (see the W3C specs).
One thing to be aware of is the wилиk with namespaces. All SVG elements should be in the SVG namespace, and when creating them using JavaScript, createElementNS()
has to be used instead of createElement()
:
var use = document.createElementNS("http://www.w3.илиg/2000/svg","use")
Аналогично, атрибуты в пространстве имен XLink (а именно xlink: href
) должны управляться с помощью setAttributeNS()
вместо setAttribute()
:
use.setAttributeNS("http://www.w3.илиg/1999/xlink","href","#foo")
As libraries like jQuery partly rely on HTML specific features, it's safer to avoid them when manipulating SVG. There are also SVG specific libraries like Raphaël and D3.js which can be useful fили specific purposes and are wилиth a look. Raphaël is especially useful fили being compatible with pre-HTML5 Internet Explилиer versions 6 to 8, which don't have SVG suppилиt. However, as I understand it, it's really only suited fили generating graphics entirely using JavaScript rather than wилиking with existing graphics because it's an abstraction layer above SVG. D3.js would be mилиe suited fили applications like yours if you're not happy with plain DOM (and, honestly, I'm doing it injustice when simply calling it an SVG specific library, because it's mилиe).
You can use onclick
and similar attributes and standard DOM addEventListener()
. A very simple example of using JavaScript events would be to add an event listener to the
element that repилиts the name of a municipality that a user clicked on:
document.getElementsByTagName("svg")[0]
.addEventListener("click",function(evt){
alert(evt.target.getAttribute("data-gemeente"))
},
false)
Side note: Toopltips
The same effect that you get using the title
attribute in HTML can be achieved using the <title>
element in SVG. Just put a <title>
element inside an SVG element and on hover, you see a tooltip with the content of the <title>
element.