zoukankan      html  css  js  c++  java
  • 获取、失去焦点时改变样式 【js读书笔记】

      为了能让用户清洗的知道现在输入的事那一项,我们可以改变焦点所在的输入框的样式。

      一般有两种方案,①修改class ② 行内样式

     1 <!DOCTYPE html>
     2 <html>
     3     <head>
     4         <meta charset="UTF-8">
     5         <title>获取、失去焦点时改变样式</title>
     6     </head>
     7     <body>
     8         <h2>获取、失去焦点时改变样式</h2>
     9         <input type='text' value='修改样式' data-fClass='fboder'
    10             data-bClass = 'bboder' data-fCss = '{"color":"red"}'
    11             data-bCss = '{"color":"green"}' id='autoUpdateCss' />
    12     </body>
    13     <script type="text/javascript">
    14         window.onload=function(){
    15             
    16             var strToJson=function(str){//将字符转为json对象
    17                 return typeof JSON=="object"?JSON.parse(str):(new Function("return"+str))();
    18             };
    19             
    20             var setCss=function(_this,cssOption){//设置样式
    21                 if(!_this||_this.nodeType===3||_this.nodeType===8||!_this.style){
    22                     return;
    23                 }
    24                 for(var cs in cssOption){
    25                     _this.style[cs]=cssOption[cs];
    26                 }
    27                 return _this;
    28             };
    29             
    30             var _autoUpdateCss=document.getElementById("autoUpdateCss"),
    31                 _fCss=_autoUpdateCss.getAttribute("data-fCss"),
    32                 _fClass=_autoUpdateCss.getAttribute("data-fClass"),
    33                 _bClass=_autoUpdateCss.getAttribute("data-bClass"),
    34                 _bCss=_autoUpdateCss.getAttribute("data-bCss");
    35             
    36             _autoUpdateCss.onfocus=function(){//获取焦点之后的样子
    37                 _fCss&&setCss(this,strToJson(_fCss));
    38                 _fClass&&(this.className=_fClass);
    39             }
    40             
    41             _autoUpdateCss.onblur=function(){//失去焦点之后的样子
    42                 _bCss&&setCss(this,strToJson(_bCss));
    43                 _bClass&&(this.className=_bClass);
    44             }
    45             
    46         };
    47     </script>
    48 </html>
    使用strToJson()将字符串转换成JSON,默认会检测浏览器是否支持JSON,如果支持,就直接调用内置的转换函数,否则利用函数的特性转换

    “想要越幸运,就要越努力”
  • 相关阅读:
    转:高并发高负载系统架构
    用java模拟银行柜台排队
    转:VS2010与SVN
    转:MySQL导入.sql文件及常用命令
    转:Mongodb中随机的查询文档记录
    转:Thumbs.db是什么文件?是病毒吗?怎么处理?
    转:OWASP发布Web应用程序的十大安全风险
    转:Top 10 Algorithms for Coding Interview
    编写C# Windows服务,用于杀死Zsd.exe进程
    转:eclipse载入extjs4出现内存溢出错误的解决方法
  • 原文地址:https://www.cnblogs.com/HollyLearning/p/5442579.html
Copyright © 2011-2022 走看看