Ris*_*shi 5 html javascript css jquery svg
使用此 Stackoverflow问题和第一个答案,我能够在文档准备好的情况下将SVG图像转换为内联svg.我也可以从CSS引用它的路径'元素来添加悬停笔划.
我要完成的下一件事是添加onclick到每个路径,而不必将其添加到svg文件本身.我假设因为CSS可以识别每个路径的类,我也应该能够在javascript中识别每个路径的ID,但是我无法弄清楚如何.这是我的代码:
<body>
<div id="mapSideBar" class="left">
</div>
<div id="mapMain" class="left">
<img id = "mapImg" src="canada2.svg" class="logo" />
</div>
</body>
Run Code Online (Sandbox Code Playgroud)
我有上面的链接中提到的功能将其转换为内联SVG,我的路径有ids - path1,path2,path3和path4.我试着在jQuery(document).ready()
函数中添加以下内容:
var $paths = jQuery(document).find('path');
$paths.each(function() {
(this).click(onImgClick((this).id));
});
Run Code Online (Sandbox Code Playgroud)
只是为了看看我是否可以在每条路径上获得一个句柄,我不能.有没有我缺少的东西,或者甚至有办法为每条路径分配onclick事件处理程序?
谢谢你,Rishi
这是一个有效的解决方案:JSFiddle
HTML:
<img class="svg" src="http://upload.wikimedia.org/wikipedia/en/e/e5/My_Little_Pony_Friendship_is_Magic_logo.svg"/>
Run Code Online (Sandbox Code Playgroud)
CSS:
svg path:hover {
fill: red !important;
}
Run Code Online (Sandbox Code Playgroud)
JavaScript:
/*
* Replace all SVG images with inline SVG
*/
jQuery('img.svg').each(function(){
var $img = jQuery(this);
var imgID = $img.attr('id');
var imgClass = $img.attr('class');
var imgURL = $img.attr('src');
jQuery.get(imgURL, function(data) {
// Get the SVG tag, ignore the rest
var $svg = jQuery(data).find('svg');
// Add replaced image's ID to the new SVG
if(typeof imgID !== 'undefined') {
$svg = $svg.attr('id', imgID);
}
// Add replaced image's classes to the new SVG
if(typeof imgClass !== 'undefined') {
$svg = $svg.attr('class', imgClass+' replaced-svg');
}
// Remove any invalid XML tags as per http://validator.w3.org
$svg = $svg.removeAttr('xmlns:a');
// Replace image with new SVG
$img.replaceWith($svg);
// Add an handler
jQuery('path').each(function() {
jQuery(this).click(function() {alert(jQuery(this).attr('id'));});
});
});
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6739 次 |
最近记录: |