Sta*_*ann 70 html javascript css jquery
我可以在css中设置初始文本输入大小,如下所示:
width: 50px;
Run Code Online (Sandbox Code Playgroud)
但是当我打字直到达到例如200px时,我希望它能够增长.这可以用直接的css,html完成,最好不用javascript吗?
当然也要发布你的js/jquery解决方案,但如果没有它们就可以做到 - 这很棒.
我试试这里:
Joe*_*Joe 92
以下是仅包含CSS和内容可编辑的示例:
CSS
span
{
border: solid 1px black;
}
div
{
max-width: 200px;
}
Run Code Online (Sandbox Code Playgroud)
HTML
<div>
<span contenteditable="true">sdfsd</span>
</div>
Run Code Online (Sandbox Code Playgroud)
Pau*_*aul 32
我刚刚为你写了这篇文章,我希望你喜欢它:)不保证它是跨浏览器,但我认为它是:)
(function(){
var min = 100, max = 300, pad_right = 5, input = document.getElementById('adjinput');
input.style.width = min+'px';
input.onkeypress = input.onkeydown = input.onkeyup = function(){
var input = this;
setTimeout(function(){
var tmp = document.createElement('div');
tmp.style.padding = '0';
if(getComputedStyle)
tmp.style.cssText = getComputedStyle(input, null).cssText;
if(input.currentStyle)
tmp.style.cssText = input.currentStyle.cssText;
tmp.style.width = '';
tmp.style.position = 'absolute';
tmp.innerHTML = input.value.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'")
.replace(/ /g, ' ');
input.parentNode.appendChild(tmp);
var width = tmp.clientWidth+pad_right+1;
tmp.parentNode.removeChild(tmp);
if(min <= width && width <= max)
input.style.width = width+'px';
}, 1);
}
})();
Run Code Online (Sandbox Code Playgroud)
如果您将 span 设置为 display: inline-block,自动水平和垂直调整大小效果很好:
<span contenteditable="true"
style="display: inline-block;
border: solid 1px black;
min-width: 50px;
max-width: 200px">
</span>
Run Code Online (Sandbox Code Playgroud)
如何以编程方式修改输入的size属性?
在语义上(imo),这个解决方案比接受的解决方案更好,因为它仍然使用输入字段进行用户输入,但它确实引入了一些jQuery.Soundcloud为它们的标记做了类似的事情.
<input size="1" />
$('input').on('keydown', function(evt) {
var $this = $(this),
size = parseInt($this.attr('size'), 10),
isValidKey = (evt.which >= 65 && evt.which <= 90) || // a-zA-Z
(evt.which >= 48 && evt.which <= 57) || // 0-9
evt.which === 32;
if ( evt.which === 8 && size > 0 ) {
// backspace
$this.attr('size', size - 1);
} else if ( isValidKey ) {
// all other keystrokes
$this.attr('size', size + 1);
}
});
Run Code Online (Sandbox Code Playgroud)