在textarea中替换脚本后如何保持光标位置相同?

问题描述

我尝试了几种解决方案,将直引号替换为智能引号后,光标自动移至行尾,从而解决了该错误

我已经修复了逗号,句点,双空格,分号和破折号。但是我不能继续引号。

我的目标是:

  1. 自动用智能引号替换直引号
  2. 将当前位置保持在原位置。
function slideShow() {

    const backgroundImg = [
        "https://x1.jpg","https://x2.jpg","https://x3.jpg"
    ];
    const backgroundImgLength = backgroundImg.length;

    let i = 1;

    setInterval(function () {
        
        if (i <= backgroundImgLength) {

            setimage(i - 1);       

            i++;

            if (i > backgroundImgLength) {
                i = 1;
            }
        }
    },5000);

    function setimage(ref) {
        $('.header-section').css('background-image','url(' + backgroundImg[ref] + ')');
    }

}

setTimeout(function() {
    slideShow();
},4000); 
        window.addEventListener('DOMContentLoaded',function(e) {
          var area = document.getElementById("textarea1");

          var getCount = function (str,search) {
              return str.split(search).length - 1;
          };

          var replace = function (search,replaceWith) {
              if (typeof(search) == "object") {
                  area.value = area.value.replace(search,replaceWith);
                  return;
              }
              if (area.value.indexOf(search) >= 0) {
                  var start = area.selectionStart;
                  var end = area.selectionEnd;
                  var textBefore = area.value.substr(0,end);
                  var lengthDiff = (replaceWith.length - search.length) * getCount(textBefore,search);
                  area.value = area.value.replace(search,replaceWith);
                  area.selectionStart = start + lengthDiff;
                  area.selectionEnd = end + lengthDiff;
              }
          };

          area.addEventListener("input",function (e) {
              replace(",",");
              replace(" ;",";");
              replace(" .",".");
              replace("  "," ");
              replace("--","—");
              replace(/(^|[-\u2014\s(\["])'/g,"$1\u2018");
              replace(/'/g,"\u2019");
              replace(/(^|[-\u2014/\[(\u2018\s])"/g,"$1\u201c");
              replace(/"/g,"\u201d");
          });
        });

这是因为正则表达式用于引号,所以才这样做吗?如何正确执行此操作?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)