2013-04-26 26 views
4

如何將默認文本放入用戶無法刪除的輸入html元素(輸入開始處的文本文本)。 我想要的第二件事情就是將光標固定在這個固定的文本之後。Html將固定文本放在輸入文本上

+2

您需要使用JavaScript才能做到這一點。你爲什麼想要這樣做?爲什麼不在輸入前添加標籤?我認爲這種方法會混淆用戶。 – 2013-04-26 09:15:45

+0

'placeholder'怎麼樣? – Vucko 2013-04-26 09:16:09

+1

@Vucko佔位符在聚焦並輸入文本時被刪除。 – 2013-04-26 09:16:35

回答

1

絕對將文本放在字段的開頭,然後向字段添加左填充,直到光標排到正確的位置。看到這裏的例子: http://www.accessfinancialservices.co.uk/calculators/mortgage-calculator/

+0

YES文本必須在輸入中,第一部分固定文本中的文本,但用戶可以在固定文本後添加一些文本。 – Brahim 2013-04-26 09:33:44

+0

在後端做到這一點嗎?或者在表單提交後與js一起完成。 – matpol 2013-04-26 09:53:27

18

試試這個可能會對你有所幫助。

http://jsfiddle.net/pZLcg/

<div class="input-box"> 
    <input value="" autofocus="autofocus"/> 
    <span class="unit">£</span> 
</div> 
4

我知道這個問題已經回答了,但這裏是另一種方式來做到這一點。

<!DOCTYPE html> 
<html> 
<head> 
    <style> 
    #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*/ 
    } 
    </style> 
</head> 

<body> 
    <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> 
</body> 
</html> 

我測試了這個代碼..

Firefox 22 
Google Chrome 28 
Internet Explorer 10 
Safari 5 
Opera 15 
-5

只使用佔位符=「名稱」 例如:

+0

佔位符屬性不固定,當您鍵入它時,將替換佔位符與文本中輸入的內容 – Nicholas 2015-04-14 10:32:00

4

如果你想只有你可以輸入元素解決這個問題使用內聯svg背景。

http://codepen.io/anon/pen/pJoBya

HTML

<input type="text" /> 

CSS

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; 
} 

要在Internet Explorer,這工作,你需要encodeURIComponent方法的SVG圖像 http://pressbin.com/tools/urlencode_urldecode/

+0

非常酷的解決方案。至少在Chrome中,用戶縮放時甚至文本大小也會增加。 – hgoebl 2017-01-24 13:36:57

0
var requiredText = 'http://'; 
    $('#site').on('input',function() { 
     if (String($(this).val()).indexOf(requiredText) == -1) { 
      $(this).val(requiredText); 
     } 
    });