如何使元素连续运行或永不停止运行?

时间:2019-02-08 16:19:21

标签: javascript html

你好,我是JS和HTML的新手,正试图使它类似于文本编辑器组件,例如Monaco Editor。
运作方式-
Ventify()函数接受一个元素,并添加一个装订线和一个文本区域。因此,我在此函数中创建了一个if语句,该语句检查textarea中的行数并相应地创建装订线。我在执行此操作时遇到的问题是该函数仅在加载文本时对文本进行编号,因为该函数结束了。有没有一种方法可以使function / if语句永无止境。
这是该项目的代码笔:https://codepen.io/chrismg/pen/qgxOxg
JS(带有JQuery):

function Ventify(element){
    element.style.display="flex";
    element.style.flexDirection = "row";
    var gutter = document.createElement("div");
    var textarea = document.createElement("textarea");
    gutter.className = "gutter";
    textarea.className = "ventiEditor";
    gutter.style.width = "100px";
    gutter.style.height = "100%";
    gutter.style.backgroundColor = "#1d252c";

    textarea.style.width = "calc(100% - 100px)";
    textarea.style.overflowY= "scroll";
    textarea.style.whiteSpace = "pre";
    textarea.style.resize = "none";
    textarea.style.height = "100%";
    textarea.style.margin = "0px 0px 0px 0px"
    textarea.style.border = "0px solid rgb(255,255,255)"
    textarea.style.backgroundColor = "#1d252c";
    textarea.value = "\n\n\n\n";
    element.appendChild(gutter);
    element.appendChild(textarea);
    if(gutter.childNodes.length != $(textarea).val().split("\n").length){
        while(gutter.childNodes.length < $(textarea).val().split("\n").length){
            var gutterChild = document.createElement("div");
            gutterChild.style.width = "100%";
            gutterChild.style.color = "rgba(58,74,88,1)"
            gutterChild.style.textAlign = "center";
            gutter.appendChild(gutterChild);
            gutterChild.innerHTML = `${gutter.childNodes.length}`
        }
    }
}
    Ventify(document.getElementsByClassName("container")[0])

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test Ground</title>
    <style>
        html,body{
            height: 100%;
            margin: 0px 0px 0px 0px;
        }
        .container{
            height: 50%;
        }
    </style>
</head>
<body>
    <div class="container"></div>
</body>
</html>

3 个答案:

答案 0 :(得分:0)

更好的方法是在输入或文本区域上使用onKeydown(或类似事件)事件。像下面的例子一样

function handle(){
  let element = document.getElementById('inp').value;
  console.log(element, 'called on change')
}
<input id='inp' onKeydown=handle() />

在您的代码中可以使用setInterval。并在需要停止时清除间隔。

setInterval(Ventify(document.getElementsByClassName("container")[0]),200)

Codepen

答案 1 :(得分:0)

您可以使用附加在input元素上的<textarea>事件在用户输入时执行任务。参见How to continually add typed characters to a variable?

如果您尝试检查元素childListattributes是否已更改,则可以使用MutationObserver。参见call function on change of value inside <p> tag

答案 2 :(得分:0)

您可以在用户每次更新内容时使用onchange事件来激发您的功能。

const element = document.getElementsByClassName("container")[0];
element.onchange = (event) => Ventify(event.target, 200);