【发布时间】:2011-03-19 11:55:07
【问题描述】:
我正在嵌入式 SVG 中进行一些查找和替换。我正在创建的网络打印服务的一部分。 我在 SVG 中有文本标签,例如 {name}、{title}、{phone} 等。
我编写了一个脚本来替换这些值,它会实时更新嵌入的 SVG。它目前工作正常。
它使用 jQuery SVG 插件来加载 SVG。
// Callback after loading external document
function loadDone(svg, error) {
svg.configure({viewBox: '0 0 315 180', width: 579, height: 331}, true); //resize the svg. viewBox must be the same size as the initial width defined in the SVG
var textElems = document.getElementsByTagNameNS('http://www.w3.org/2000/svg', 'tspan');
var doc = document.getElementById('svgload').contentDocument;
for (var i = 0; i < textElems.length; i++) {
var id = textElems[i].childNodes[0].nodeValue;
id = id.replace("{",""); //remove brackets {}
id = id.replace("}","");
alert(id);
$("#formContainer").append('<p>' + capitalize(id) + ': <input type="text" id="' + id + '" class="replace" />\n');
$("#formContainer").append('<input type="hidden" id="' + id + 'PrevVal" value="{' + id + '}" /></p>');
}
$('.replace').keyup(function() {
var prevValID = $(this).attr("id") + "PrevVal"; //determine the hidden input id
var oldVal = $("#"+prevValID).val(); //set oldVal to the hidden input value, first time it's {id}
var currentVal = $(this).val(); //set the currentVal to the user inputted value
changeText(oldVal,currentVal); //swap the oldVal with the currentVal
$('#'+prevValID).attr("value",currentVal); //set the hidden input value to the last inputted user value
svg.configure({viewBox: '0 0 315 180', width: 579, height: 331}, true); //"resize" to svg to clear the text. some browsers break the new text until the svg is "zoomed", or in this case, resized
});
function changeText(oldVal,newVal) { //swap the values inside the SVG file
for (var i = 0; i < textElems.length; i++) {
if (textElems[i].childNodes[0].nodeValue == oldVal) {
textElems[i].childNodes[0].nodeValue = newVal;
}
}
}
}
function capitalize(str) { //capitalize first letter of words
var firstLetter = str.slice(0,1);
return firstLetter.toUpperCase() + str.substring(1);
}
虽然有一些错误。例如,由于我正在创建隐藏的 div 来存储 SVG 文本的先前值,因此可以创建这样一种情况:在两个文本框中键入相同的内容会创建两个相同的 ID,然后进一步键入会更新嵌入的 SVG 中的两个文本元素。它也不喜欢包含空格的标签,例如 {full name} 与 {name}。
关于如何清理这整个事情的任何建议?我知道我应该能够检测标签(搜索 {}),然后获取与它们关联的文本或 tspan id 并以这种方式更新节点值,但是,我有严重的编码块,不能完全开始它!
【问题讨论】:
-
您知道,IE 对在浏览器中渲染 SVG 的支持非常有限。
-
是的,我知道。我想我最终会使用 svgweb。实际上,虽然我对支持 IE 客户端不感兴趣。主要是学生使用我的服务。
标签: javascript jquery svg