【问题标题】:Preserve whitespace in HTML select element options using "white-space: pre" NOT working使用“空白:pre”在 HTML 选择元素选项中保留空白不起作用
【发布时间】:2012-07-02 20:37:21
【问题描述】:

我的问题来自 HTML 下拉选择无法在其选项中保留多个连续的空格。这是一个示例测试用例和结果。

“white-space:pre”类 CSS 似乎只适用于除选择元素选项之外的任何 HTML 元素。是否有任何文献或案例表明此类问题?

print "<style>.keepwhitespace { white-space: pre }</style>
<p class='keepwhitespace'>abc   def</p>
abc   def
<br/>
<br/>select and options with keepwhitespace
<select onchange=\"alert('\''+this.value+'\' '+this.value.length)\" class='keepwhitespace'>
<option class='keepwhitespace'>Any </option>
<option class='keepwhitespace'>abc   def </option>
<option class='keepwhitespace'> Any  </option>
<option class='keepwhitespace'>abc def </option>
</select>
<br/>select with keepwhitespace
<select onchange=\"alert('\''+this.value+'\' '+this.value.length)\" class='keepwhitespace'>
<option >Any </option>
<option >abc   def </option>
<option> Any  </option>
<option>abc def </option>
</select>
<br/>options with keepwhitespace
<select onchange=\"alert('\''+this.value+'\' '+this.value.length)\">
<option class='keepwhitespace'>Any </option>
<option class='keepwhitespace'>abc   def </option>
<option class='keepwhitespace'> Any  </option>
<option class='keepwhitespace'>abc def </option>
</select>";

结果如下:

预加载 从“p”元素标签中可以看出(以及我尝试使用的任何其他标签,都可以很好地使用“空白” CSS 样式格式化文本。但是选择没有。

在选择时查看项目值字符串和字符串长度(长度应该是 10 而不是 7,'abc def' 的长度是 8 个字符)

【问题讨论】:

    标签: html whitespace html-select


    【解决方案1】:

    表单输入通常映射到其相关的本机操作系统控件,因此很难设置样式。防止空格在&lt;option&gt;s 中折叠成1 个空格的常用解决方法是使用&amp;nbsp; 而不是通常的空格。

    例如。您的选择之一是:

    <option>&nbsp;Any&nbsp;&nbsp;</option>
    

    要获得更多自定义外观,您可以完全隐藏真正的选择元素并用自定义标记和 javascript 替换它。

    【讨论】:

    • 感谢@Teoulas,对您的建议有所了解。我将所有空格 ' ' 替换为 ' '对每个选项值使用 str_replace $str1 = str_replace(" ", "&amp;nbsp;",$str1); .....&lt;option &gt;$str1&lt;/option&gt;。有点糟糕,这些问题至少没有记录在案……花了一段时间才找到你的建议;)!再次感谢
    • 使用此解决方案需要注意的一点是,由于它是非中断空间,因此不会中断。这意味着您执行此操作的任何长文本都将保留在一行上。如果您知道要修改的文本很短,那么此解决方案效果很好。在我的情况下,它不适用于通常很长的用户输入。
    【解决方案2】:

    从服务器端语言动态创建 SELECT 列表时,接受的答案是正确的。但是,如果您想使用 document.createElement 函数在 Javascript 中创建选项列表(这可能是使用输入时最安全的方法,但您无法始终完全控制),那么您可以使用以下方法:

    var someSelectElement = document.getElementById("id_of_select_element");
    var optionSt = "Some spaces     go here.";
    var tObj = document.createElement("OPTION");
    
    tObj.value = 1; // whatever value you need.
    tObj.title = "Whatever title you want to appear when hovering over the option";
    
    tObj.text = decodeURI(optionSt.replace(/ /g, "%C2%A0")); // decodeURI is the key here.
    
    // Then add it to an already existing HTML select element...
    someSelectElement.appendChild(tObj);
    

    【讨论】:

      猜你喜欢
      • 2020-11-17
      • 1970-01-01
      • 2011-12-10
      • 1970-01-01
      • 2018-05-17
      • 1970-01-01
      • 1970-01-01
      • 2012-01-26
      相关资源
      最近更新 更多