当前位置: 移动技术网 > IT编程>网页制作>Html5 > HTML5 placeholder(空白提示)属性介绍

HTML5 placeholder(空白提示)属性介绍

2019年07月25日  | 移动技术网IT编程  | 我要评论
原文地址:
演示地址:
原文日期: 2010年08月09日
翻译日期: 2013年8月6日
浏览器引入了许多的html5 特性: 有些是基于html的,有些是javascript apis形式的,但都很有用。其中我最喜欢的一个就是为input元素引入了placeholder属性。
placeholder属性显示引导性文字直到输入框获取输入焦点,当有了用户输入内容后引导性内容将会自动隐藏。你肯定见过用javascript实现的这种技术成千上万次了,但是来自html5的原生支持一般来说会更好一些。
html 代码 如下:

复制代码
代码如下:

<input type="text" name="address" placeholder="请输入常住地址...">

你要做的仅仅是添加一个placeholder属性域,以及一些引导性的文字内容,不需要额外的javascript脚本来实现这种效果,是不是感觉很棒?
测试 placeholder 的支持度
(注意这是2010年的文章,到现在,2013年,主流浏览器应该都支持了.)
既然 placeholder 是一个新的功能,那么测试浏览器的支持是很有必要的。js代码如下:

复制代码
代码如下:

// 在js中创建一个input元素,并判断元素有没有一个叫做placeholder的属性
// 如果浏览器支持的话,那么在js里面引用的dom就会存在这个属性
function hasplaceholdersupport() {
var input = document.createelement('input');
return ('placeholder' in input);
}

而如果浏览器不支持placeholder特性,那你就需要一个fallback策略来处理,比如mootools,dojo,或者其他javascript工具。(现在dojo可以用的少了,国内更多的是jquery和extjs。)

复制代码
代码如下:

/* jquery 代码,当然,记得引入jquery的库哦*/
$(function(){
if(!hasplaceholdersupport()){
// 获取address元素
var $address = $("input[name='address']");
placeholder = $address.attr("placeholder");
// 绑定 focus事件
$address.bind('focus',function(){
if(placeholder == $address.val()){
$address.val('');
}
});
// 失去焦点事件
$address.bind('blur',function(){
if('' == $address.val()){
$address.val(placeholder);
}
});
}
});

placeholder 是浏览器另一个伟大的附加属性用于取代js片段,你甚至可以编辑html5的placeholder样式.
全部代码如下:

复制代码
代码如下:

<!doctype html>
<html>
<head>
<title> html5 placeholder属性演示 </title>
<meta name="generator" content="editplus">
<meta name="author" content="renfufei@qq.com">
<meta name="description" content="original=http://davidwalsh.name/html5-placeholder">
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
// 在js中创建一个input元素,并判断元素有没有一个叫做placeholder的属性
// 如果浏览器支持的话,那么在js里面引用的dom就会存在这个属性
function hasplaceholdersupport() {
var input = document.createelement('input');
return ('placeholder' in input);
}
/* jquery 代码,当然,记得引入jquery的库哦*/
$(function(){
if(!hasplaceholdersupport()){
// 获取address元素
var $address = $("input[name='address']");
placeholder = $address.attr("placeholder");
// 绑定 focus事件
$address.bind('focus',function(){
if(placeholder == $address.val()){
$address.val('');
}
});
// 失去焦点事件
$address.bind('blur',function(){
if('' == $address.val()){
$address.val(placeholder);
}
});
}
});
</script>
</head>
<body>
<div>
<form method="post" action="">
<input type="text" name="address" placeholder="请输入常住地址...">
<input type="submit" value="测试">
</form>
</div>
</body>
</html>

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网