Javascript-文字后的占位符

时间:2018-08-18 10:10:00

标签: javascript html css

在Google计算器上,当您单击平方根或sin时,它会显示一个“占位符”括号,括号一结束便消失。 HTML中有一个简单的内置方法吗?

Googles Calculator

1 个答案:

答案 0 :(得分:2)

您不能将HTML元素放在input的值中,但是可以使它看起来像您自己。

Google伪造一个input标记而不是放置一个真实的标记,因此,只要您专注于该标记,只要键入,它们就会附加您键入的文本,并在需要时加上括号,这样看起来会更好。它们的跨度是所有文本,然后是括号。

我们可以利用contenteditable属性来从另一个元素创建假输入,然后根据需要在:after伪元素中添加假括号:

(插入括号后面的逻辑仍然很简单,因为它不是重点。)

let fakeInput = document.getElementById("fakeinput");

fakeInput.addEventListener("keypress", e => {
  if(e.key == "(") {
    fakeInput.setAttribute("parenses", ")".repeat((fakeInput.getAttribute("parenses")||"").length+1));
  } else if (e.key == ")") {
    fakeInput.setAttribute("parenses", ")".repeat(Math.max((fakeInput.getAttribute("parenses")||"").length-1, 0)));
  }
});
[contenteditable="true"] {
  width: 100%;
  font-size: 24px;
  border-radius: 4px;
  border: 1px solid grey;
  padding: 0 10px;
  display: block;
  box-sizing: border-box;
  transition: box-shadow 0.25s linear;
}

#fakeinput:after {
  content: attr(parenses);
  color: gray;
}
<div parenses="" id="fakeinput" contenteditable="true"></div>

请注意,由于我们无法在JS中修改伪元素,因此请在CSS中使用attrparenses属性来修改:after伪元素的内容。 / p>

我们可以将假输入包装在包含假输入和包含括号的跨度的父级中,将样式应用于父级,然后单击父级,我们将重点放在假输入上并应用括弧到跨度,而不是使用包含可能更清晰的括号的属性。


另一种解决方案是使元素向右浮动,并在需要时使用)的值,如果键入了右括号,则只需删除该元素即可。以下只是一个可以改进的非常基本的示例,但它显示了总体思路:

let parens = document.getElementById("parenthesis");
document.getElementById("inputtext").addEventListener("keypress", e => {
    //More sophisticated code to check for unclosed parenthesises instead of this one:
    if(e.key == "(") {
        parens.classList.add("visible");
    } else if (e.key == ")") {
        parens.classList.remove("visible");
    }
});
html {
   box-sizing:border-box;
}

*, *:after, *:before {box-sizing: inherit;}

#parenthesis
{
    position: absolute;
    right: 5px;
    top: 50%;
    transform: translateY(-50%);
    color:gray;
    display: none;
    font-size: 16px;
}
#parenthesis.visible {
    display: block;
}

input
{
    border:0;
    display: inline-block;
    text-align: right;
    width: 100%;
    padding: 5px;
    font-size: 16px;
}

input:focus
{
    outline-width:0;
}

.inputholder
{
    border:1px solid black;
    padding:5px;
    width: 200px;
    position: relative;
}
<div class="inputholder">
    <span id="parenthesis">)</span>
    <input type="text" id="inputtext"/>
</div>

相关问题