為什么用class不行,用id就可以了?
<!DOCTYPE?html?PUBLIC?"-//W3C//DTD?XHTML?1.0?Transitional//EN"?"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html?xmlns="http://www.w3.org/1999/xhtml"> <head> <meta?http-equiv="Content-Type"?content="text/html;?charset=utf-8"?/> <title>無標題文檔</title> <style?type="text/css"> .box{ width:100px; height:100px; background:#CF6; border:2px?solid; position:relative; left:-50px; } </style> </head> <body> <div?class="box"> </div> <script?type="text/javascript"> window.onload=function(){ var?box=document.getElementsByClassName('box'); box.onmouseover=function(){ startMove(); } } function?startMove(){ setInterval(function(){ var?box=document.getElementsByClassName('box'); box.style.left=box.offsetLeft+10+'px'; },30) } ? </script> </body> </html>
上面的代碼沒有效果,如果把box改成id的就可以了,這是為什么呢
2017-04-03
你要是非要這么用的話,改寫成var?box=document.getElementsByClassName('box')[0];
不加[0]的話,box得到的是一個dom對象數(shù)組,之后需要for循環(huán)遍歷,你再回頭把js關于dom章節(jié)的知識點看看吧,基礎知識不掌握就急著做效果是不行的