開始打字時如何離開占位符并向前延伸
就像我輸入 100 個空格和 INX
100 INX
這樣當我輸入 100 時,INX 向前移動,完全輸入變為
100 INX
<!DOCTYPE html>
<html>
<body>
<h1>Extend placeholder forward</h1>
<input type="text" id="left" name="left" oninput="right.value = left.value; return true;" placeholder="INX"/>
<input type="text" id="right" name="right" oninput="left.value = right.value; return true;" placeholder="INX" disabled />
</body>
</html>
uj5u.com熱心網友回復:
不,您不能修改本機占位符的行為。
一種帶有定位、偽元素和 css 變數的 hacky 解決方法:
document.querySelector('#left').addEventListener('input', function() {
this.parentElement.style.setProperty('--val', "'" this.value "'");
document.querySelector('#right').value = this.value ? this.value ' INX' : '';
});
#div1, #div2 {
position: relative;
display: block;
width: fit-content;
width: -moz-fit-content;
--val: '';
font-family: sans-serif;
font-size: 14px;
}
#div1::after {
content: var(--val) ' INX';
position: absolute;
left: 3px;
top: 1px;
bottom: 1px;
pointer-events: none;
line-height: 20px;
}
#left, #right {
font-family: inherit;
font-size: inherit;
caret-color: black;
}
#left {
color: transparent;
}
<h1>Extend placeholder forward</h1>
<div id="div1"><input type="text" id="left" name="left" maxlength="18" /></div>
<div id="div2"><input type="text" id="right" name="right" placeholder="INX" disabled /></div>
uj5u.com熱心網友回復:
用輸入元素做事很棘手——例如,你不能附加偽元素。
采取稍微不同的方法,如果您使用 contenteditable div 而不是輸入,您可以附加一個帶有 INX 作為內容的 after 元素,它會在用戶鍵入時在實際輸入之前移動:
div {
display: inline-block;
width: auto;
border: 1px solid black;
border-radius: 5px;
background: #eeeeee;
padding: 5px;
}
div::after {
content: ' INX';
}
<div contenteditable></div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/420854.html
標籤:
上一篇:使用影片樣式更新div元素的內容
