为什么doctype会阻止Javascript工作?

为什么doctype会阻止Javascript工作?,javascript,html,xhtml,doctype,Javascript,Html,Xhtml,Doctype,在Stack Overflow方面一些优秀人士的帮助下,我能够在一个简单的文本html页面上修复Javascript。以下是最终代码: <html> <head> </head> <body> <img id="imageid" onmouseover="bigImg(this)" onmouseout="normalImg(this)" src="images/bra

在Stack Overflow方面一些优秀人士的帮助下,我能够在一个简单的文本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>

var img=document.getElementById('imageid');
var normsizeimg=img.style.width;
var bigwidth=600;
函数bigImg(x)
{x.style.width=bigwidth;}
函数normalImg(x){x.style.width=normsizeimg;}
将鼠标悬停在图像上,图像会放大。简单

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


这一点很重要,因为我希望能够使用
margin:0 auto
将一个无表格的页面居中,并且这仅在您有Doctype时有效。

请不要为此使用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>

测试
#imageid{宽度:200px}
#imageid:悬停{宽度:600px}

请不要为此使用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>

测试
#imageid{宽度:200px}
#imageid:悬停{宽度:600px}

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

这项工作:

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

function normalImg ( x ) { 
  x.style.width = normsizeimg + 'px';
}
现场演示:


或者,这也适用于:

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

function normalImg ( x ) { 
  x.width = normsizeimg;
}
现场演示:



然而,正如@Jan的回答所示,增加悬停图像的大小可以通过CSS单独完成。

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

这项工作:

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

function normalImg ( x ) { 
  x.style.width = normsizeimg + 'px';
}
现场演示:


或者,这也适用于:

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

function normalImg ( x ) { 
  x.width = normsizeimg;
}
现场演示:



然而,正如@Jan的回答所显示的,增加悬停图像的大小可以通过CSS单独完成。

什么浏览器?在控制台中是否看到错误?完全停止工作?我在这里感觉到怪癖模式与标准模式的错误。DOCTYPE会影响框model@tkone:IE、FF、Chrome和Safari浏览器都会出现这种情况。什么浏览器?在控制台中是否看到错误?完全停止工作?我在这里感觉到怪癖模式与标准模式的错误。DOCTYPE会影响框model@tkone:IE、FF、Chrome和SafariYup都会出现这种情况,这是正确的解决方案。知道这与标准模式和怪癖模式有关。是的,这是正确的解决方案。我知道这和标准模式和怪癖模式有关。谢谢你的建议。谢谢你的建议。