繁体   English   中英

使用JS将“占位符”文本添加到元素

[英]Adding 'placeholder' text to an element using JS

-

已经有一些帖子( 就像这个 ),但它们并不能真正适应这种情况。

我有一个基于CRM中自定义字段动态生成文本内容的短代码,用于显示其软件的用户序列号,如下所示:

序列号字段

序列号的直接父容器是#copyTarget2

当容器为空时,它仍然在页面上呈现但没有内容,如下所示:

空序列号容器

我需要使用“占位符”文本填充空容器,但不能填写您可以输入的类型,只是为了显示只显示的文本 - “ 没有活动的序列号”

最后,当填充字段时,需要隐藏占位符文本,只要它不可见并且不影响短代码生成的文本,它隐藏的方式并不重要。


我也试图改编这个JS小提琴: http//jsfiddle.net/davidThomas/LAfN2/

从:

$('input:text').each(
    function(i,el) {
        if (!el.value || el.value == '') {
            el.placeholder = 'placeholdertext';
            /* or:
            el.placeholder = $('label[for=' + el.id + ']').text();
            */
        }
    });

至:

jQuery('#copyTarget2').each(
    function(i,el) {
        if (!el.value || el.value == '') {
            el.placeholder = 'No valid serial number.';
            /* or:
            el.placeholder = $('label[for=' + el.id + ']').text();
            */
        }
    });

CSS和HTML对我来说就像第二语言,但我是JS的新手,所以我可以稍微修改一下代码但是我还不能写(但是),我想知道最好的JS解决方案是什么来实现这个以及为什么?

我认为你需要像span元素中的placeholder而不是输入标记。使用一些css。请看下面的片段。并使用jquery函数的attr()添加属性

CSS content

 jQuery('#copyTarget2').each( function(i, el) { if (!$(el).text() || $(el).text().trim() == '') { $(el).attr('placeholder', 'No valid serial number.') /* or: el.placeholder = $('label[for=' + el.id + ']').text(); */ } }); 
 span:empty:before { font-size: 12; color: #9E9E9E; line-height: 40px; text-indent: 20px; content: attr(placeholder); display: block; border: 1px solid grey; } span{ position:absolute;/*or fix as your wish with respect to parent element*/ width:200px;/*or fix as your wish with respect to parent element*/ height:50px;/*or fix as your wish with respect to parent element*/ } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span id="copyTarget2"></span> 

使用:empty和:before with attribute在占位符为空时设置它。

 [data-placeholder]:empty:before { color: #AAA; content: attr(data-placeholder); } 
 <span data-placeholder="My placeholder"></span> <br/> <span data-placeholder="My placeholder">I have text</span> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM