Internet Explorer의 입력 자리 표시 자
HTML5는 요소에 placeholder
속성을 도입하여 input
회색으로 표시된 기본 텍스트를 표시 할 수 있습니다.
슬프게도 IE 9를 포함한 Internet Explorer는이를 지원하지 않습니다.
자리 표시 자 시뮬레이터 스크립트가 이미 있습니다. 일반적으로 기본 텍스트를 입력 필드에 넣고 회색을 표시하고 입력 필드에 초점을 맞추 자마자 다시 제거하여 작동합니다.
이 방법의 단점은 자리 표시 자 텍스트가 입력 필드에 있다는 것입니다. 그러므로:
- 스크립트는 입력 필드가 비어 있는지 쉽게 확인할 수 없습니다
- 플레이스 홀더를 데이터베이스에 삽입하지 않으려면 서버 측 처리에서 기본값을 확인해야합니다.
자리 표시 자 텍스트가 입력 자체에없는 솔루션을 원합니다.
"웹 양식 : 입력 자리"보고에서의 섹션 HTML5 크로스 브라우저 Polyfills , 하나의 I 톱이었다 jQuery를 - HTML5-자리 .
IE9로 데모를 시도해 보니 <input>
스팬으로 감싸고 자리 표시 자 텍스트로 레이블을 오버레이하는 것처럼 보입니다 .
<label>Text:
<span style="position: relative;">
<input id="placeholder1314588474481" name="text" maxLength="6" type="text" placeholder="Hi Mom">
<label style="font: 0.75em/normal sans-serif; left: 5px; top: 3px; width: 147px; height: 15px; color: rgb(186, 186, 186); position: absolute; overflow-x: hidden; font-size-adjust: none; font-stretch: normal;" for="placeholder1314588474481">Hi Mom</label>
</span>
</label>
다른 심도 있지만, 나는 그것들을 모두 보지 않았습니다. 그중 하나 인 Placeholders.js 는 자신을 "종속성이 없음 (따라서 대부분의 자리 표시 자 폴리 필 스크립트와 달리 jQuery를 포함 할 필요가 없음")로 광고합니다.
편집 : "어떻게" "어떻게"에 더 관심이있는 사람들 을 위해, 이것을 수행하는 jQuery 플러그인을 만드는 과정을 안내하는 고급 HTML5 자리 표시 자 폴리 필 을 만드는 방법.
또한 Firefox 및 Chrome과 다른 IE10에서 자리 표시 자 텍스트가 포커스에서 사라지는 방법에 대한 설명 은 IE10에서 자리 표시 자 유지를 참조하십시오 . 이 문제에 대한 해결책이 있는지 확실하지 않습니다.
내 경험 중 가장 좋은 것은 https://github.com/mathiasbynens/jquery-placeholder ( html5please.com 권장 )입니다. http://afarkas.github.com/webshim/demos/index.html 은 훨씬 더 광범위한 폴리 필 라이브러리 중에서 좋은 솔루션을 제공합니다.
jQuery 구현을 사용하면 제출할 때 기본값을 쉽게 제거 할 수 있습니다. 아래는 예입니다.
$('#submit').click(function(){
var text = this.attr('placeholder');
var inputvalue = this.val(); // you need to collect this anyways
if (text === inputvalue) inputvalue = "";
// $.ajax(... // do your ajax thing here
});
나는 당신이 오버레이를 찾고 있다는 것을 알고 있지만, 당신은이 경로의 용이함을 선호 할 것입니다 (이제 위에서 쓴 것을 알고 있습니다). 그렇다면 내 프로젝트를 위해 이것을 작성했으며 실제로 훌륭하게 작동하며 (jQuery 필요) 전체 사이트에 구현하는 데 몇 분 정도 걸립니다. 처음에는 회색 텍스트, 초점이 맞으면 밝은 회색, 입력 할 때 검은 색을 제공합니다. 또한 입력 필드가 비어있을 때마다 자리 표시 자 텍스트를 제공합니다.
먼저 양식을 설정하고 입력 태그에 자리 표시 자 속성을 포함시킵니다.
<input placeholder="enter your email here">
이 코드를 복사하여 placeholder.js로 저장하십시오.
(function( $ ){
$.fn.placeHolder = function() {
var input = this;
var text = input.attr('placeholder'); // make sure you have your placeholder attributes completed for each input field
if (text) input.val(text).css({ color:'grey' });
input.focus(function(){
if (input.val() === text) input.css({ color:'lightGrey' }).selectRange(0,0).one('keydown', function(){
input.val("").css({ color:'black' });
});
});
input.blur(function(){
if (input.val() == "" || input.val() === text) input.val(text).css({ color:'grey' });
});
input.keyup(function(){
if (input.val() == "") input.val(text).css({ color:'lightGrey' }).selectRange(0,0).one('keydown', function(){
input.val("").css({ color:'black' });
});
});
input.mouseup(function(){
if (input.val() === text) input.selectRange(0,0);
});
};
$.fn.selectRange = function(start, end) {
return this.each(function() {
if (this.setSelectionRange) { this.setSelectionRange(start, end);
} else if (this.createTextRange) {
var range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', start);
range.select();
}
});
};
})( jQuery );
하나의 입력에만 사용하려면
$('#myinput').placeHolder(); // just one
브라우저가 HTML5 자리 표시 자 속성을 지원하지 않는 경우 사이트의 모든 입력 필드에 구현하는 것이 좋습니다.
var placeholder = 'placeholder' in document.createElement('input');
if (!placeholder) {
$.getScript("../js/placeholder.js", function() {
$(":input").each(function(){ // this will work for all input fields
$(this).placeHolder();
});
});
}
IE에서 몇 가지 제안을 시도하고 문제를 본 후에는 다음과 같이 작동합니다.
https://github.com/parndt/jquery-html5-placeholder-shim/
내가 좋아하는 것-당신은 단지 js 파일을 포함합니다. 시작할 필요가 없습니다.
- IE9 +에서만 작동
다음 솔루션은 자리 표시 자 속성을 사용하여 입력 텍스트 요소에 바인딩합니다. IE에 대해서만 자리 표시 자 동작을 에뮬레이트하고 제출되지 않은 경우 제출시 입력 값 필드를 지 웁니다.
이 스크립트를 추가하면 IE는 HTML5 자리 표시자를 지원하는 것 같습니다.
$(function() {
//Run this script only for IE
if (navigator.appName === "Microsoft Internet Explorer") {
$("input[type=text]").each(function() {
var p;
// Run this script only for input field with placeholder attribute
if (p = $(this).attr('placeholder')) {
// Input field's value attribute gets the placeholder value.
$(this).val(p);
$(this).css('color', 'gray');
// On selecting the field, if value is the same as placeholder, it should become blank
$(this).focus(function() {
if (p === $(this).val()) {
return $(this).val('');
}
});
// On exiting field, if value is blank, it should be assigned the value of placeholder
$(this).blur(function() {
if ($(this).val() === '') {
return $(this).val(p);
}
});
}
});
$("input[type=password]").each(function() {
var e_id, p;
if (p = $(this).attr('placeholder')) {
e_id = $(this).attr('id');
// change input type so that the text is displayed
document.getElementById(e_id).type = 'text';
$(this).val(p);
$(this).focus(function() {
// change input type so that password is not displayed
document.getElementById(e_id).type = 'password';
if (p === $(this).val()) {
return $(this).val('');
}
});
$(this).blur(function() {
if ($(this).val() === '') {
document.getElementById(e_id).type = 'text';
$(this).val(p);
}
});
}
});
$('form').submit(function() {
//Interrupt submission to blank out input fields with placeholder values
$("input[type=text]").each(function() {
if ($(this).val() === $(this).attr('placeholder')) {
$(this).val('');
}
});
$("input[type=password]").each(function() {
if ($(this).val() === $(this).attr('placeholder')) {
$(this).val('');
}
});
});
}
});
간단한 기능을 제안합니다.
function bindInOut(element,value)
{
element.focus(function()
{
if(element.val() == value) element.val('');
}).
blur(function()
{
if(element.val() == '') element.val(value);
});
element.blur();
}
그것을 사용하려면 다음과 같이 호출하십시오.
bindInOut($('#input'),'Here your value :)');
이 방법을 사용하여 매우 간단한 해결책을 찾았습니다.
http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html
jquery 해킹이며 내 프로젝트에서 완벽하게 작동했습니다.
당신이 사용할 수있는 :
var placeholder = 'search here';
$('#search').focus(function(){
if ($.trim($(this).val()) === placeholder){
this.value ='';
}
}).blur(function(){
if ($.trim($(this).val()) === ''){
this.value = placeholder;
}
}).val(placeholder);
이처럼 간단합니다.
$(function() {
...
var element = $("#selecter")
if(element.val() === element.attr("placeholder"){
element.text("").select().blur();
}
...
});
I have written a jquery plugin to solve this problem.. it's free..
JQuery Directory:
http://plugins.jquery.com/project/kegles-jquery-placeholder
Site: www.kegles.com.br/jquery-placeholder/
I came up with a simple placeholder JQuery script that allows a custom color and uses a different behavior of clearing inputs when focused. It replaces the default placeholder in Firefox and Chrome and adds support for IE8.
// placeholder script IE8, Chrome, Firefox
// usage: <input type="text" placeholder="some str" />
$(function () {
var textColor = '#777777'; //custom color
$('[placeholder]').each(function() {
(this).attr('tooltip', $(this).attr('placeholder')); //buffer
if ($(this).val() === '' || $(this).val() === $(this).attr('placeholder')) {
$(this).css('color', textColor).css('font-style','italic');
$(this).val($(this).attr('placeholder')); //IE8 compatibility
}
$(this).attr('placeholder',''); //disable default behavior
$(this).on('focus', function() {
if ($(this).val() === $(this).attr('tooltip')) {
$(this).val('');
}
});
$(this).on('keydown', function() {
$(this).css('font-style','normal').css('color','#000');
});
$(this).on('blur', function() {
if ($(this).val() === '') {
$(this).val($(this).attr('tooltip')).css('color', textColor).css('font-style','italic');
}
});
});
});
Placeholdr is a super-lightweight drop-in placeholder jQuery polyfill that I wrote. It's less than 1 KB minified.
I made sure that this library addresses both of your concerns:
Placeholdr extends the jQuery $.fn.val() function to prevent unexpected return values when text is present in input fields as a result of Placeholdr. So if you stick with the jQuery API for accessing your fields' values, you won't need to change a thing.
Placeholdr listens for form submits, and it removes the placeholder text from fields so that the server simply sees an empty value.
Again, my goal with Placeholdr is to provide a simple drop-in solution to the placeholder issue. Let me know on Github if there's anything else you'd be interested in having Placeholdr support.
TO insert the plugin and check the ie is perfectly workedjquery.placeholder.js
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="jquery.placeholder.js"></script>
<script>
// To test the @id toggling on password inputs in browsers that don’t support changing an input’s @type dynamically (e.g. Firefox 3.6 or IE), uncomment this:
// $.fn.hide = function() { return this; }
// Then uncomment the last rule in the <style> element (in the <head>).
$(function() {
// Invoke the plugin
$('input, textarea').placeholder({customClass:'my-placeholder'});
// That’s it, really.
// Now display a message if the browser supports placeholder natively
var html;
if ($.fn.placeholder.input && $.fn.placeholder.textarea) {
html = '<strong>Your current browser natively supports <code>placeholder</code> for <code>input</code> and <code>textarea</code> elements.</strong> The plugin won’t run in this case, since it’s not needed. If you want to test the plugin, use an older browser ;)';
} else if ($.fn.placeholder.input) {
html = '<strong>Your current browser natively supports <code>placeholder</code> for <code>input</code> elements, but not for <code>textarea</code> elements.</strong> The plugin will only do its thang on the <code>textarea</code>s.';
}
if (html) {
$('<p class="note">' + html + '</p>').insertAfter('form');
}
});
</script>
Here is a pure javascript function (no jquery needed) that will create placeholders for IE 8 and below and it works for passwords as well. It reads the HTML5 placeholder attribute and creates a span element behind the form element and makes the form element background transparent:
/* Function to add placeholders to form elements on IE 8 and below */
function add_placeholders(fm) {
for (var e = 0; e < document.fm.elements.length; e++) {
if (fm.elements[e].placeholder != undefined &&
document.createElement("input").placeholder == undefined) { // IE 8 and below
fm.elements[e].style.background = "transparent";
var el = document.createElement("span");
el.innerHTML = fm.elements[e].placeholder;
el.style.position = "absolute";
el.style.padding = "2px;";
el.style.zIndex = "-1";
el.style.color = "#999999";
fm.elements[e].parentNode.insertBefore(el, fm.elements[e]);
fm.elements[e].onfocus = function() {
this.style.background = "yellow";
}
fm.elements[e].onblur = function() {
if (this.value == "") this.style.background = "transparent";
else this.style.background = "white";
}
}
}
}
add_placeholders(document.getElementById('fm'))
<form id="fm">
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<textarea name="description" placeholder="Description"></textarea>
</form>
NOTE: the author of this polyfill claims it "works in pretty much any browser you can imagine" but according to the comments that's not true for IE11, however IE11 has native support, as do most modern browsers
Placeholders.js is the best placeholder polyfill I've seen, is lightweight, doesn't depend on JQuery, covers other older browsers (not just IE), and has options for hide-on-input and run-once placeholders.
i use jquery.placeholderlabels. It's based on this and can be demoed here.
works in ie7, ie8, ie9.
behavior mimics current firefox and chrome behavior - where the the "placeholder" text remains visible on focus and only disappears once something is typed in the field.
I created my own jQuery plugin after becoming frustrated that the existing shims would hide the placeholder on focus, which creates an inferior user experience and also does not match how Firefox, Chrome and Safari handle it. This is especially the case if you want an input to be focused when a page or popup first loads, while still showing the placeholder until text is entered.
https://github.com/nspady/jquery-placeholder-labels/
참고URL : https://stackoverflow.com/questions/5522164/input-placeholders-for-internet-explorer
'Programming' 카테고리의 다른 글
Eclipse 용 Bash 스크립트 플러그인? (0) | 2020.05.23 |
---|---|
Java에서 컴퓨터의 CPU, 메모리 및 디스크 사용량을 어떻게 모니터링합니까? (0) | 2020.05.23 |
jQuery : position ()과 offset ()의 차이점 (0) | 2020.05.23 |
파일이 디스크에서 변경되었을 때 Emacs가 모든 버퍼를 자동으로 새로 고치는 방법? (0) | 2020.05.23 |
반응 – 폼 요소 상태를 형제 / 부모 요소로 전달하는 올바른 방법? (0) | 2020.05.23 |