Html HTML5 占位符在焦点上消失

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8574356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 12:06:18  来源:igfitidea点击:

HTML5 placeholder disappears on focus

htmljquery-pluginssafarifocusplaceholder

提问by Dan Abramov

Is there a freely available jQuery plugin that changes placeholderbehavior to match HTML5 spec?

是否有免费提供的 jQuery 插件可以更改placeholder行为以匹配 HTML5 规范?

Before Focus
chrome unfocused placeholder

对焦前
镀铬未聚焦占位符

On Focus Good (Safari)
safari focused placeholder

聚焦好 (Safari)
Safari 聚焦占位符

On Focus Bad (Chrome, Firefox)
chrome focused placeholder

焦点不好(Chrome,Firefox)
镀铬重点占位符

You can what your browser does with this simple fiddle.

您可以使用这个简单的 fiddle来完成浏览器的操作。

HTML5 draft spec says:

HTML5 草案规范说

User agents should present this hint to the user, after having stripped line breaks from it, when the element's value is the empty string and/orthe control is not focused (e.g. by displaying it inside a blank unfocused control and hiding it otherwise).

当元素的值是空字符串和/或控件没有聚焦(例如,通过在空白的未聚焦控件中显示它并以其他方式隐藏它)时,用户代理应该在从它剥离换行符之后向用户呈现这个提示。

The "/or" is new in current draft so I suppose that's why Chrome and Firefox don't support it yet. See WebKit bug #73629, Chromium bug #103025.

“/or”在当前草案中是新的,所以我想这就是 Chrome 和 Firefox 还不支持它的原因。请参阅WebKit 错误 #73629Chromium 错误 #103025

采纳答案by Dan Abramov

Stefano labels

斯特凡诺标签

Stefano J. Attardiwrote a nice jQuery plugin that just does that.
It is more stable than Robert's and also fades to a lighter grey when the field gets focused.

Stefano J. Attardi写了一个很好的 jQuery 插件,就是这样做的。
它比罗伯特的更稳定,并且在场聚焦时会逐渐变浅为浅灰色。



I modified his plugin to read placeholderattribute as opposed to manually creating a span.
This fiddlehas complete code:

我修改了他的插件来读取placeholder属性,而不是手动创建一个span.
这个小提琴有完整的代码:

HTML

HTML

<input type="text" placeholder="Hello, world!">

JS

JS

// Original code by Stefano J. Attardi, MIT license

(function($) {
    function toggleLabel() {
        var input = $(this);

        if (!input.parent().hasClass('placeholder')) {
            var label = $('<label>').addClass('placeholder');
            input.wrap(label);

            var span = $('<span>');
            span.text(input.attr('placeholder'))
            input.removeAttr('placeholder');
            span.insertBefore(input);
        }

        setTimeout(function() {
            var def = input.attr('title');
            if (!input.val() || (input.val() == def)) {
                input.prev('span').css('visibility', '');
                if (def) {
                    var dummy = $('<label></label>').text(def).css('visibility','hidden').appendTo('body');
                    input.prev('span').css('margin-left', dummy.width() + 3 + 'px');
                    dummy.remove();
                }
            } else {
                input.prev('span').css('visibility', 'hidden');
            }
        }, 0);
    };

    function resetField() {
        var def = $(this).attr('title');
        if (!$(this).val() || ($(this).val() == def)) {
            $(this).val(def);
            $(this).prev('span').css('visibility', '');
        }
    };

    var fields = $('input, textarea');

    fields.live('mouseup', toggleLabel); // needed for IE reset icon [X]
    fields.live('keydown', toggleLabel);
    fields.live('paste', toggleLabel);
    fields.live('focusin', function() {
        $(this).prev('span').css('color', '#ccc');
    });
    fields.live('focusout', function() {
        $(this).prev('span').css('color', '#999');
    });

    $(function() {
       $('input[placeholder], textarea[placeholder]').each(
           function() { toggleLabel.call(this); }
       );
    });

})(jQuery);

CSS

CSS

.placeholder {
  background: white;
  float: left;
  clear: both;
}
.placeholder span {
  position: absolute;
  padding: 5px;
  margin-left: 3px;
  color: #999;
}
.placeholder input, .placeholder textarea {
  position: relative;
  margin: 0;
  border-width: 1px;
  padding: 6px;
  background: transparent;
  font: inherit;
}

/* Hack to remove Safari's extra padding. Remove if you don't care about pixel-perfection. */
@media screen and (-webkit-min-device-pixel-ratio:0) {
    .placeholder input, .placeholder textarea { padding: 4px; }
}

回答by Dan Abramov

Robert Nyman discusses the problem and documents his approach in his blog.
This fiddlethat has all the neccessary HTML, CSS and JS.

Robert Nyman在他的博客中讨论了这个问题并记录了他的方法。
这个小提琴包含所有必要的 HTML、CSS 和 JS。

enter image description here

在此处输入图片说明

Unfortunately, he solves the problem by changing value.
This will not work by definition if placeholdertext is itself a valid input.

不幸的是,他通过更改value.
如果placeholder文本本身是一个有效的输入,这根据定义是行不通的。

回答by Andrey Kuzmin

I found this question by googling out the solution to the same problem. It seems that existing plugins either don't work in elder browsers or hide placeholder on focus.

我通过谷歌搜索同一问题的解决方案发现了这个问题。似乎现有的插件要么在旧浏览器中不起作用,要么在焦点上隐藏占位符。

So I decided to roll on my own solution while trying to combine best parts from existing plugins.

所以我决定推出我自己的解决方案,同时尝试结合现有插件的最佳部分。

You may check it out hereand open an issue if you face any problems.

如果您遇到任何问题,您可以在此处查看并打开一个问题。

回答by Logan

How about something simple like this? On focus save out the placeholder attribute value and remove the attribute entirely; on blur, put the attribute back:

像这样简单的东西怎么样?在焦点上保存占位符属性值并完全删除该属性;在模糊时,将属性放回去:

$('input[type="text"]').focus( function(){
  $(this).attr("data-placeholder",$(this).attr('placeholder')).removeAttr("placeholder");
});
$('input[type="text"]').blur( function(){
  $(this).attr("placeholder",$(this).attr('data-placeholder'));
});   

回答by Fabian

I wrote my own css3 only solution. See if that fullfills all your needs.

我编写了自己的 css3 唯一解决方案。看看这是否满足您的所有需求。

http://codepen.io/fabiandarga/pen/MayNWm

http://codepen.io/fabiandarga/pen/MayNWm

This is my solution:

这是我的解决方案:

  1. the input element is set to "required"
  2. an aditional span element for the placeholder is needed. This element is moved on top of the input element (position: absolute;)
  3. with css selectors the input element is tested for validity (required fields are invalid as long as there is no input) and the placeholder is then hidden.
  1. 输入元素设置为“必需”
  2. 占位符需要额外的 span 元素。此元素移动到输入元素的顶部(位置:绝对;)
  3. 使用 css 选择器测试输入元素的有效性(只要没有输入,必填字段就无效),然后隐藏占位符。

Pitfall:The placeholder is blocking mouseevents to the input! This problem is circumvented by hiding the placeholder element when the mouse is inside the parent (wrapper).

陷阱:占位符阻止了输入的鼠标事件!当鼠标位于父级(包装器)内时,可以通过隐藏占位符元素来规避此问题。

<div class="wrapper">
  <input txpe="text" autofocus="autofocus" required/>
  <span class="placeholder">Hier text</span>
</div>

.placeholder {
  display: none;
  position: absolute;
  left: 0px;
  right: 0;
  top: 0px;
  color: #A1A1A1;
}
input:invalid + .placeholder {
  display: block;  /* show the placeholder as long as the "required" field is empty */
}
.wrapper:hover .placeholder {
  display: none; /* required to guarantee the input is clickable */
}

.wrapper{
  position: relative;
  display: inline-block;
}

回答by herchila

Maybe you can try with Float Label Pattern :)

也许您可以尝试使用浮动标签模式:)

See Float labels in CSS

请参阅CSS 中的浮动标签