请注意,当我将 svg 代码内联到 HTML 文件时,我不会收到此错误。 我需要在 HTML 中使用许多 svg 文件,因此将所有内容都放在一个文件中会非常不方便。
在我的一个 JavaScript 函数中,以下是我使用的代码:
var svgT = Snap("#redBar");
var line = svgT.select("#line"); // exception occurs here
这是 svg 代码,供其自己的文件中引用:
<svg version="1.1" id="redBar" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 113.9 3.7" style="enable-background:new 0 0 113.9 3.7;" xml:space="preserve">
<style type="text/css">
.st0{fill:url(#SVGID_1_);}
</style>
<g id="line">
<linearGradient id="SVGID_1_" gradientUnits="userSpaceOnUse" x1="1.239177e-04" y1="29.3381" x2="113.9399" y2="29.3381" gradientTransform="matrix(1 0 0 1.3293 0 -37.1699)">
<stop offset="1.075269e-02" style="stop-color:#EC1C24"/>
<stop offset="0.1548" style="stop-color:#EC2026"/>
<stop offset="0.2961" style="stop-color:#ED2C2A"/>
<stop offset="0.436" style="stop-color:#EE3F32"/>
<stop offset="0.5" style="stop-color:#EF4B37"/>
<stop offset="0.5483" style="stop-color:#EE4334"/>
<stop offset="0.7058" style="stop-color:#ED2D2B"/>
<stop offset="0.8586" style="stop-color:#EC2026"/>
<stop offset="1" style="stop-color:#EC1C24"/>
</linearGradient>
<path class="st0" d="M113,3.7H1c-0.5,0-1-0.4-1-1L0,1c0-0.5,0.4-1,1-1l112,0c0.5,0,1,0.4,1,1v1.7C113.9,3.2,113.5,3.7,113,3.7z"/>
</g>
</svg>
现在,当我在 JavaScript 中运行该函数来选择组元素 (#line) 时,出现以下异常:
Uncaught TypeError: Cannot read property of 'select' of null
看来我必须做一些其他事情才能从 svg 中正确读取元素。
有没有人处理过使用 Snap.svg 操作 svg 文件,可以给我一些其他可以尝试的提示?
编辑:
我还尝试使用 Snap.load()
关于windows onload函数。
var svgT;
var line;
window.onload = function() {
Snap.load("/svg/RedBar-01.svg", function (f) {
var g = f.select("g");
svgT = Snap("#redBar");
line = svgT.select("#line");
});
我尝试使用 Snap.animate()
加载后单击按钮:
line.animate({
fill: "pink",
transform: 't0,0'
}, 1000);
此时我似乎没有从 .animate() 函数得到任何响应。
编辑2:
我当前的 JS 代码:
window.onload = function() {
Snap.load("/svg/RedBar-01.svg", function (f) {
var s = Snap(800,800);
s.append(f);
var l = Snap("#redBar");
var line = l.select("#line");
line.animate({
fill: "pink",
transform: 't0,0'
}, 1000);
});
最佳答案
确保你append()加载了svg片段f。
一般格式为
var s = Snap(800,800); // or Snap('#mySvg') an existing svg element, not a div
Snap.load( filename, function( fragment ) {
s.append( f ); //add the loaded svg fragment into the DOM
var element = s.select('#myId');
element.animate(....)
});
还要确保没有某些 css 样式取代了 svg 属性。
关于javascript - 使用 Snap.Select 时 SVG 未捕获类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40289793/