获取、失去焦点时改变样式 【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,如果支持,就直接调用内置的转换函数,否则利用函数的特性转换

posted @ 2016-04-28 14:32  HollyLearningNotes  阅读(647)  评论(0编辑  收藏  举报