关于document.getElementById取值问题 老是取不到值

<html>

<head>

<script  language = "javascript" type = "text/javascript" >

      function  marry()

 {

    this.x = 0;

this.y = 0;

    this.move = function (derect){

       switch(derect)

{

case  0  : window.alert("向上走");

   var marry2 = document.getElementById(sb);

window.alert(sb.s2.left);

   break;

case  1  : window.alert("向右走");

   break;

case  2  : window.alert("向下走");

   break;

case  3  : window.alert("向左走");

   break;

}  

}

 //document.getElementById(id)  DOM对象  对要进行获取的元素配一个ID 通过 document.getElementById(id)来获得这个元素

 //这里 因为我们要改变 Img的left和right 首先要对img进行获取

 }

 var  marry1 = new marry();

     

 function ps(derect)

  {

       switch(derect)

  

  {

           case  0  : marry1.move(0);

   break;

case  1  :  marry1.move(1);

   break;

case  2  :  marry1.move(2);

   break;

case  3  : marry1.move(3);

   break;     

  }

  }    


</script>


<style type=text/css>

body{

border:1px solid red;

margin:0 auto;


width:1000px;

}

.s1

{

width:800px;

height:300px;

background-color:red;

position:absolute;

margin:0 auto;

}

 .s2

{

  width :50px;

  height:30px;

  position:absolute;

   left:200px;

.table1

{

border : 1px solid red ;

width:500px;

height:200px;

margin:0 auto;

}

.s3

{

  position:absolute;

  top:300px;

  left:200px;

}


</style>

</head>

<body>

<div class = s1>

<img id ="sb" src = images/1.jpg  class = s2 />

</div>

<div class = s3 >

<table class = table1>

<tr colspan = 3><td>游戏键盘</td></tr>

<tr><td>****</td><td><input type = button  value = ↑ onclick = ps(0)  /></td><td>****</td></tr>

<tr><td><input type = button  value = ←  onclick = ps(3)  /></td><td>****</td><td>****</td></tr>

<tr><td>****</td><td>****</td><td><input type = button  value = →  onclick = ps(1)    /></td></tr>

<tr><td>****</td><td><input type = button  value = ↓  onclick = ps(2) /></td><td>****</td></tr>

</table>



</div>



</body>

</html>

问  我如果把s2 里面的样式用style写到img里面,能把sb.s2.left的值提取出来 但是用类选择器写的话就提不出来了 ,请问是哪里出问题了呀 

慕粉3585463
浏览 5557回答 7
7回答

小草1434

你确定你的html的代码是这样的???

宝慕林2233867

程序读代码是由上到下开始读的,所以尽可能的把代码写下面,基本上都是写在</body>之前的,或者就加一个window.onload=function(){代码},还有就是id名称是个字符串,要加引号的;要不然就成变量了

super_mb

是的,这个确实要写在标签内才能取得,要不你就在js中给它初始化位置,原因我也说不上来,但是一年前就发现了这个坑,单独写在css中取不到。

Instant

原生js,是你代码的问题吧,这个基本不会有问题
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript