首页 > 代码库 > :focus匹配当前获取焦点的元素(小示例)

:focus匹配当前获取焦点的元素(小示例)

源代码

 1 <!DOCTYPE html> 2 <html> 3 <head> 4   <script src="http://code.jquery.com/jquery-latest.js"></script> 5 </head> 6 <body>
7 <style> 8 .focused { 9 background:#C93;10 }11 </style>

12 <div id="content">13 <input tabIndex="1">14 <input tabIndex="2">15 <select tabIndex="3">16 <option>select menu</option>17 </select>18 <div tabIndex="4">19 a div20 </div>21 </div>22 23 <script>24 $( "#content" ).delegate( "*", "focus blur", function( event ) { /*为content的子元素添加“focus blur”事件*/25 var elem = $( this ); /*获取当前所有元素并赋值到elem*/26 setTimeout(function() { /*执行setTimeout函数*/27 elem.toggleClass( "focused", elem.is( ":focus" ) ); /*设置被选元素的类进行切换 elem.is判断当前是否获取焦点。如果没有,则获取焦点*/28 }, 0);29 });30 </script>31 32 </body>33 </html>

 

:focus匹配当前获取焦点的元素(小示例)