为什么Doctypes会阻止Javascript工作?

时间:2012-03-04 14:18:46

标签: html javascript-events xhtml doctype

在stackoverflow的一些好人的帮助下,我能够在简单的文本html页面上修复javascript。这是最终的代码:

<html>
<head>
</head>
<body>
  <img id="imageid" onmouseover="bigImg(this)" onmouseout="normalImg(this)" src="images/bracelet-1.jpg" alt="image" width="200" > 
  <script type="text/javascript">
     var img = document.getElementById('imageid');
     var normsizeimg = img.style.width;
     var bigwidth = 600;

     function bigImg(x)
     { x.style.width = bigwidth; }
     function normalImg(x) { x.style.width = normsizeimg; }
  </script>
</body>

</html>

将鼠标悬停在图像上方,然后将其放大。简单。

但是,如果我们在代码顶部添加任何Doctype语句,脚本将停止工作。无论是HTML4 Doctype,HTML5 Doctype还是XHTML Doctype风格之一都无关紧要。有人可以告诉我为什么会发生这种情况以及可以做些什么呢?

这很重要,因为我希望能够使用margin:0 auto将无表格页面居中,只有当你有Doctype时才能使用。

2 个答案:

答案 0 :(得分:4)

事实证明,在标准模式下,您无法向x.style.width提供数字。您必须提供以'px'结尾的字符串。

这有效:

function bigImg ( x ) {
  x.style.width = bigwidth + 'px';
}

function normalImg ( x ) { 
  x.style.width = normsizeimg + 'px';
}

现场演示: http://jsfiddle.net/e3d2P/


或者,这也有效:

function bigImg ( x ) {
  x.width = bigwidth;
}

function normalImg ( x ) { 
  x.width = normsizeimg;
}

现场演示: http://jsfiddle.net/e3d2P/1/


然而,正如@ Jan的答案所示,只使用CSS就可以增加悬停时图像的大小。

答案 1 :(得分:1)

请不要使用javascript,使用CSS!它更具语义性,可读性更强,性能更好。

<!doctype html>
<html>
  <head>
    <title>test</title>
    <style type="text/css">
      #imageid { width:200px }
      #imageid:hover { width:600px }
    </style>
  </head>
  <body>
    <img id="imageid" src="images/bracelet-1.jpg" alt="image"> 
  </body>
</html>
相关问题