如何将默认文本放入用户无法删除的 HTML 文本输入元素中(输入开头的固定文本)。
我想要的第二件事是光标将定位在这个固定文本之后。
Try this one. It might be helpful for you. It positions the text over the text input using absolute positioning.
.input-box {
position: relative;
}
input {
display: block;
border: 1px solid #d7d6d6;
background: #fff;
padding: 10px 10px 10px 20px;
width: 195px;
}
.unit {
position: absolute;
display: block;
left: 5px;
top: 10px;
z-index: 9;
}
<div class="input-box">
<input value="" autofocus="autofocus"/>
<span class="unit">£</span>
</div>
如果您只想使用输入元素来解决此问题,您可以使用内联 svg 背景。
http://codepen.io/anon/pen/pJoBya
要在 Internet Explorer 中进行这项工作,您需要 encodeURIComponent SVG 图像 http://pressbin.com/tools/urlencode_urldecode/
input {
background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="40" height="30"><text x="5" y="19" style="font: bold 16px Arial;">Age:</text></svg>') no-repeat;
border: 1px solid #555;
box-sizing: border-box;
font: 16px "Arial";
height: 30px;
padding-left: 50px;
width: 300px;
}
<input type="text" />
我知道这个问题已经得到解答,但这是另一种方法。
我用..测试了这段代码
Firefox 22
Google Chrome 28
Internet Explorer 10
Safari 5
Opera 15
#text_container {
padding: 1px;
/*To make sure that the input and the label will not overlap the border, If you remove this line it will not display correctly on Opera 15.0*/
border: 1px solid activeborder;
/*Create our fake border :D*/
}
#text_container>label {
color: activeborder;
background-color: white;
-webkit-touch-callout: none;
/*Make the label text unselectable*/
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
}
#text_container>input {
border: none;
/*We have our fake border already :D*/
}
<span id="text_container">
<!-- Don't break the following line to avoid any gaps between the label text and the input text -->
<label>http://www.</label><input type="text" />
</span>
var requiredText = 'https://';
$('#site').on('input', function() {
if (String($(this).val()).indexOf(requiredText) == -1) {
$(this).val(requiredText);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="site" />
将文本绝对定位在字段的开头,然后向字段添加左填充,直到光标对齐到正确的位置。请参阅此处的示例: http ://www.accessfinancialservices.co.uk/calculators/mortgage-calculator/
您也可以使用 bootstrap 来做到这一点:
div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">@</div>
</div>
<input type="text" class="form-control" id="inlineFormInputGroupUsername" placeholder="Username">
</div>
你可以在这里查看。(查看用户名字段)
只需使用 placeholder="Name" 例如: