实时编辑嵌入网站中的 SVG 文本

发布于 2024-10-23 14:13:06 字数 2441 浏览 0 评论 0原文

我正在嵌入式 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 并以这种方式更新节点值,但是,我有严重的编码块,无法完全开始它!

I'm doing some find and replace in embedded SVGs. Part of a web to print service I'm creating.
I have text tags inside the SVG like {name}, {title}, {phone}, etc.

I wrote a script to replace these values and it live updates the embedded SVG. It currently works alright.

It's using the jQuery SVG plugin to load the 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);
}

There are some bugs though. For example, since I'm creating hidden divs to store the previous value of the SVG text one can create a situation where typing the same thing into two text boxes creates two identical IDs and then further typing updates both text elements in the embedded SVG. It also doesn't like tags that have spaces in them, like {full name} versus {name}.

Any suggestions on how to clean this whole thing up? I know I should be able to detect tags (searching for {}) and then get the text or tspan id associated with them and update the node value that way, however, I've got severe coding block and can't quite start on it!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

静谧幽蓝 2024-10-30 14:13:06

设法将其精简为:

// 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 textID = textElems[i].getAttribute('id');
    var textValue = textElems[i].childNodes[0].nodeValue;
      textValue = textValue.replace("{",""); //remove brackets {}
      textValue = textValue.replace("}","");
    $("#formContainer").append('<p style="text-transform:capitalize;">' + textValue + ': <input type="text" id="' + textID + '" class="replace" />\n');
  }

    $('.replace').keyup(function() {
      var textToChange = document.getElementById($(this).attr('id'));
      textToChange.childNodes[0].nodeValue = $(this).val();
      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
    });
}

它正在做我想要的事情。

希望这可以帮助其他想要在嵌入式 SVG 中进行文本替换的人:)

Managed to trim it down to this:

// 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 textID = textElems[i].getAttribute('id');
    var textValue = textElems[i].childNodes[0].nodeValue;
      textValue = textValue.replace("{",""); //remove brackets {}
      textValue = textValue.replace("}","");
    $("#formContainer").append('<p style="text-transform:capitalize;">' + textValue + ': <input type="text" id="' + textID + '" class="replace" />\n');
  }

    $('.replace').keyup(function() {
      var textToChange = document.getElementById($(this).attr('id'));
      textToChange.childNodes[0].nodeValue = $(this).val();
      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
    });
}

And it's doing exactly what I want.

Hopefully that helps anyone else looking to do text replacements in embedded SVG's :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文