0

我在我的应用程序中为输入框使用占位符,并为不支持占位符的浏览器使用 jquery 解决方法。然而,在大多数浏览器中,即使输入为空,占位符也会在输入处于焦点时消失。一种解决方法是在输入字段上使用透明背景,并在输入字段后面直接放置一个带有文本的跨度,并在输入内容后将背景更改为不透明。问题是我的应用程序现在有超过 3000 个输入字段。这是否可以通过运行时的 jquery 插件来做到这一点?或者我愿意接受更好的建议。请帮忙。

4

3 回答 3

1

您是否在同一页面上有 3000 个输入字段?在这种情况下,您需要以某种方式重新设计您的应用程序。

如果您在多个页面上有不同的输入,并且希望插件在需要时自动生成占位符,那么有许多不错的插件。这是一个全面的 polyfill 列表 - 只需查找“Web 表单:输入占位符”标题即可。https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills

它们中的大多数不需要为每个实例专门调用,因此您应该避免修改 3000 行代码。:)

于 2012-07-24T07:49:36.347 回答
0

这是我写的和正在使用的:

    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<style>
body{
    background-color:#DDD;
}

span.placeholder
{
    background-color:#FFF;
    color:#777;
    border-radius: 4px 4px 4px 4px;
    margin: 5px 0;
    padding: 9px 0 8px 13px;
    width: 297px;

}
input
{
    border: 1px solid #707A68;
    border-radius: 4px 4px 4px 4px;
    margin: 5px 0;
    padding: 10px;
    width: 310px;
    background:transparent;
}

</style>

<body>
<div>
    <input type="text" placeholder="hello" name="hh"/>
</div>
</body>

<script>
$('input').each(function(){

    var txt = $(this).attr('placeholder');
    var name = $(this).attr('name');
    var node = $("<span class='placeholder'>"+txt+"</span>").appendTo($(this).parent());
    $(this).before(node);
    node.css('position','absolute');
    node.css('z-index','-1');
    node.css('display','block');
    $(this).attr('placeholder','');
});
$('input').bind('keyup',function(){
    if($(this).val()=="")
        $(this).css('background','transparent');
    else
        $(this).css('background','#FFF');
});
</script>
于 2012-07-25T18:06:02.313 回答
0

我会使用 value attr 而不是逻辑将如下所示。

var input = document.createElement('input');
if(! ('placeholder' in input))
{
    $("input[placeholder]").focus(/* clear value if it is equals placeholder */);
    $("input[placeholder]").blur(/* assign placeholder if it is "" */);
    $("input[placeholder]").each(/* assign placeholder if value equals "" */)
}

您还可以更改焦点和模糊输入的样式(或类),使其看起来更像占位符。

于 2012-07-24T15:27:25.700 回答