我注意到了html/javascript的奇怪行爲。Html Doctype標籤影響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">
標籤。否則它按預期工作。
我在計算器中找到了這個question。但它似乎沒有幫助。
爲什麼會發生這種情況。你能告訴我嗎?
那麼,看我的整個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>
哪個瀏覽器? Internet Explorer **不會改變JavaScript行爲,也會根據使用的仿真/文檔模式(可以由DOCTYPE驅動)更改渲染。但是,我不認爲其他瀏覽器會這樣做。 – user113215
@ user113215我檢查過Chrome和Firefox。兩者都給出了相同的輸出。還沒有在IE上檢查過它。 – shan