Html Doctype标签影响javascript

Html Doctype tag affects javascript?

本文关键字:javascript 影响 标签 Doctype Html      更新时间:2023-09-26

我注意到html/javascript的奇怪行为。

我有这个javascript代码

window.onload = function(){
var pmap = document.getElementById('pmap'); 
var marker_sl = document.getElementById('marker_sl');
var marker_uk = document.getElementById('marker_uk');
    marker_sl.style.left = pmap.width * 70.5 / 100;
    marker_sl.style.top = pmap.height * 48 / 100;
    marker_uk.style.left = pmap.width * 44 / 100;
    marker_uk.style.top = pmap.height * 14.5 / 100;   
};

当我添加

时它不起作用
<!DOCTYPE html>

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 

标签。否则按预期工作

我在stackoverflow中发现了这个问题。但它似乎没有帮助。

为什么会这样。你能告诉我吗?

这是我的整个HTML文件

<!DOCTYPE html>
<html>
    <head></head>
<body>
<article>
<img src="images/price_map.jpg" id="pmap" />
<a href="#" id="marker_sl" style="position:absolute;display:block;"><img src="images/marker.png"  /></a>
<a href="#" id="marker_uk" style="position:absolute;display:block;"><img src="images/marker.png"  /></a>
</article>
</body>
<script type="text/javascript">
window.onload = function(){
    var pmap = document.getElementById('pmap'); 
    var marker_sl = document.getElementById('marker_sl');
    var marker_uk = document.getElementById('marker_uk');
        marker_sl.style.left = pmap.width * 70.5 / 100;
        marker_sl.style.top = pmap.height * 48 / 100;
        marker_uk.style.left = pmap.width * 44 / 100;
        marker_uk.style.top = pmap.height * 14.5 / 100;   
};
</script>
</html>

解决代码
<!DOCTYPE html>
<html>
    <head></head>
<body>
<article>
<img src="images/price_map.jpg" id="pmap" />
<a href="#" id="marker_sl" style="position:absolute;display:block;"><img src="images/marker.png"  /></a>
<a href="#" id="marker_uk" style="position:absolute;display:block;"><img src="images/marker.png"  /></a>
</article>
</body>
<script type="text/javascript">
window.onload = function(){
    var pmap = document.getElementById('pmap'); 
    var marker_sl = document.getElementById('marker_sl');
    var marker_uk = document.getElementById('marker_uk');
        marker_sl.style.left = (pmap.width * 70.5 / 100)+"px";
        marker_sl.style.top = (pmap.height * 48 / 100)+"px";
        marker_uk.style.left = (pmap.width * 44 / 100)+"px";;
        marker_uk.style.top = (pmap.height * 14.5 / 100)+"px";   
};
</script>
</html>

lefttop的CSS属性需要一个单位,如"px"。

文档声明不应该对javascript有任何影响。发布html文件,或者打开firebug,看看有哪些书使用文档声明运行它。