在 date
和 datetime-local
的输入类型中,占位符不能直接使用。
<input type="date" placeholder="Date" />
<input type="datetime-local" placeholder="Date" />
在桌面端显示mm/dd/yyyy,而在移动端则不显示任何内容。
如何显示日期的占位符文本?
在 date
和 datetime-local
的输入类型中,占位符不能直接使用。
<input type="date" placeholder="Date" />
<input type="datetime-local" placeholder="Date" />
在桌面端显示mm/dd/yyyy,而在移动端则不显示任何内容。
如何显示日期的占位符文本?
使用onfocus="(this.type='date')"
,例如:
<input required="" type="text" class="form-control" placeholder="Date" onfocus="(this.type='date')"/>
使用onfocus和onblur...这里是一个例子:
<input type="text" placeholder="Birth Date" onfocus="(this.type='date')" onblur="if(this.value==''){this.type='text'}">
这里,我尝试在input
元素中使用data
属性,并使用CSS应用了必填的占位符。
<input type="date" name="dob" data-placeholder="Date of birth" required aria-required="true" />
input[type="date"]::before {
content: attr(data-placeholder);
width: 100%;
}
/* hide our custom/fake placeholder text when in focus to show the default
* 'mm/dd/yyyy' value and when valid to show the users' date of birth value.
*/
input[type="date"]:focus::before,
input[type="date"]:valid::before { display: none }
<input type="date" name="dob" data-placeholder="Date of birth" required aria-required="true" />
<input type="text" placeholder="*To Date" onfocus="(this.type='date')" onblur="(this.type='text')" >
import {Directive, ElementRef, HostListener} from '@angular/core';
@Directive({
selector: '[appDateClick]'
})
export class DateClickDirective {
@HostListener('focus') onMouseFocus() {
this.el.nativeElement.type = 'date';
setTimeout(()=>{this.el.nativeElement.click()},2);
}
@HostListener('blur') onMouseBlur() {
if(this.el.nativeElement.value == ""){
this.el.nativeElement.type = 'text';
}
}
constructor(private el:ElementRef) { }
}
<input appDateClick name="targetDate" placeholder="buton name" type="text">
关于 React,你可以这样做。
const onDateFocus = (e) => (e.target.type = "datetime-local");
const onDateBlur = (e) => (e.target.type = "text");
.
.
.
<input
onFocus={onDateFocus}
onBlur={onDateBlur}
type="text"
placeholder="Event Date"
/>
现代浏览器使用Shadow DOM来方便输入日期和日期时间。因此,除非浏览器选择回退到text
输入,否则不会显示占位符文本。您可以使用以下逻辑来适应两种情况:
::-webkit-calendar-picker-indicator {
@apply hidden; /* hide native picker icon */
}
input[type^='date']:not(:placeholder-shown) {
@apply before:content-[attr(placeholder)];
@apply sm:after:content-[attr(placeholder)] sm:before:hidden;
}
input[type^='date']::after,
input[type^='date']::before {
@apply text-gray-500;
}
我使用了Tailwind CSS语法,因为它易于理解。让我们逐个解释:
::-webkit-calendar-picker-indicator {
@apply hidden; /* hide native picker icon */
}
使用其Shadow DOM伪元素选择器隐藏本地选择器图标(通常是日历)。
input[type^='date']:not(:placeholder-shown) {
@apply before:content-[attr(placeholder)];
@apply sm:after:content-[attr(placeholder)] sm:before:hidden;
}
选择所有未显示占位符的date
和datetime-local
输入,并执行以下操作:
::before
伪元素显示输入placeholder
文本::after
伪元素input[type^='date']::after,
input[type^='date']::before {
@apply text-gray-500;
}
为 ::before
和 ::after
伪元素添加样式。