网络编程
位置:首页>> 网络编程>> JavaScript>> 基于JS实现html中placeholder属性提示文字效果示例

基于JS实现html中placeholder属性提示文字效果示例

作者:包子源  发布时间:2023-09-07 22:50:58 

标签:JS,placeholder

本文实例讲述了基于JS实现html中placeholder属性提示文字效果。分享给大家供大家参考,具体如下:

如何通过js实现html的placeholder属性效果呢

我们需要这样做:


<!DOCTYPE html>
<html>
 <head>
   <meta charset="utf-8">
   <title>www.aspxhome.com JS实现placeholder属性效果</title>
   <script>
     function bl(){
       var a=document.getElementById("inpt");
       if(a.value.length<=0){
         a.style.color="#999999";
         a.value="请输入姓名";
       }
     }
     function fo(){
       var a=document.getElementById("inpt");
       if(a.value=="请输入姓名"){
         a.style.color="black";
         a.value="";
       }
     }
   </script>
 </head>
 <body>
   <input style="color: #999999;" value="请输入姓名" id="inpt" type="text" onblur="bl()" onfocus="fo()" />
 </body>
</html>

运行效果如下:

基于JS实现html中placeholder属性提示文字效果示例

补充:

这里再为大家补充一个jQuery实现的placeholder属性效果示例:


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>www.aspxhome.com jQuery实现placeholder属性效果</title>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<input style="color: #999999;" data-value="请输入姓名" id="inpt" type="text"/>
<script>
function placeHolder(event){
var self = $(this), selfDataValue = self.attr("data-value"), selfValue = self.val();
if(selfDataValue){
 event.type == "click" ? (selfValue == selfDataValue && (self.val("").css("color","#333"))) : (event.type == "blur" && (selfValue == "" && (self.val(selfDataValue).css("color","#A9A9A9"))))
}else{
 return false;
}
}
$("#inpt").on("click blur",placeHolder);
</script>
</body>
</html>

希望本文所述对大家JavaScript程序设计有所帮助。

来源:https://blog.csdn.net/ziwoods/article/details/49815847

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com