//事件绑定
function MyAddEvent ( obj , sEvent , fn ) {
if ( obj . attachEvent ) {
obj . attachEvent ( "on" + sEvent , fn ) ;
} else {
obj . addEventListener ( sEvent , fn , false ) ;
} ;
} ;
//事件解除绑定
function removeMyAddEvent ( obj , sEvent , fn ) {
if ( obj . detachEvent ) {
obj . detachEvent ( "on" + sEvent , fn ) ;
} else {
obj . removeEventListener ( sEvent , fn , false ) ;
} ;
} ;
1 2 3 4 5 6 | < input type = "button" value = "添加" id = "input1" / > < ul id = "ul1" style = "cursor:pointer;" > < li > 10000 < / li > < li > 20000 < / li > < li > 30000 < / li > < / ul > |
1 2 3 4 5 6 7 8 9 10 11 12 | //鼠标滑过li的状态 function mouseRun ( e , Active ) { var ev = e || window . event ; //事件对象 var target = ev . target || ev . srcElement ; //事件源 var $ li = target . nodeName . toLowerCase ( ) ; //事件源的名字 if ( $ li === "li" && Active === 1 ) { target . style . background = "Red" ; } ; if ( $ li === "li" && Active === 0 ) { target . style . background = "" ; } ; } ; |
1 2 3 | //鼠标移入、移出的效果。这样写方便可以解除绑定 function over ( e ) { mouseRun ( e , 1 ) ; } ; function out ( e ) { mouseRun ( e , 0 ) ; } ; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | //添加的li函数 function addLi ( sTarget , Now ) { var li = document . createElement ( "li" ) ; li . innerHTML = Now* 10000 ; sTarget . appendChild ( li ) ; } ; window . onload = function ( ) { var ul = document . getElementById ( "ul1" ) ; var oInput = document . getElementById ( "input1" ) ; var Now = 3 ; //绑定元素事件 MyAddEvent ( ul , "mouseover" , over ) ; MyAddEvent ( ul , "mouseout" , out ) ; MyAddEvent ( oInput , "click" , function ( ) { Now + = 1 ; addLi ( ul , Now ) } ) ; } ; window . onunload = function ( ) { //解除绑定 var ul = document . getElementById ( "ul1" ) ; removeMyAddEvent ( ul , "mouseover" , over ) ; removeMyAddEvent ( ul , "mouseout" , out ) ; } ; |