如何以“〜”开头描边字符串?

时间:2018-08-20 07:03:56

标签: javascript html css stroke

伙计们! 我需要执行以下操作。有一个要输入的字段。当他介绍以〜开头的内容时,以下所有内容都必须加框(直接在要输入的字段或下面的列表中)。如何执行呢? (没有jQuery,好吗?)

1 个答案:

答案 0 :(得分:1)

您可以做的是在要环绕的字符串部分周围添加标签

input = document.getElementById("input")
result = document.getElementById("result")

input.onkeyup = () => {
  // you need to know if the ~ is a start or end of framing
  isFramed = false
  // the resulting HTML is kept in this variable
  // adding directly to result.innerHTML cause browser to autoclose the <span> immediatly
  resultContent = ""
  
  for (let cara of input.value) {
    // if the current char is a ~
    if (cara === '~') {
      // and there is a frame
      if (isFramed) {
        // close the frame
        resultContent += "</span>"
      } else {
        // else start a new frame
        resultContent += "<span style=\"border: 1px solid black\">"
      }
      // inverse isFramed value
      isFramed = !isFramed
    } else {
      // for every other char just copy it as is
      resultContent += cara;
    }
  }

  // finaly set result's innerHTML to the builded string
  result.innerHTML = resultContent
}
<input id="input"/>
<div id="result"></div>

注意:您可以通过将<span>的样式移至CSS文件来减小HTML的大小