我有这个HTML代码:
<!DOCTYPE html>
<html>
<head>
<title>Clear a Timer</title>
<meta charset="utf-8" />
<script>
var theTimer, xPosition = 0, theImage;
function doTimer() {
theImage = document.getElementById("courseraLogo");
xPosition = xPosition + 1;
theImage.style.left = xPosition;
}
</script>
</head>
<body onload="theTimer = setInterval(doTimer, 50)">
<img src="../img/coursera.png" id="courseraLogo"
style="position:absolute; left:0">
<button onclick="clearTimeout(theTimer);">
Stop!
</button>
</body>
</html>该代码假设以50ms的间隔将图像从左向右移动。如果指定了DOCTYPE标签,则不起作用:图像不会移动。为什么会发生这种情况?与HTML版本相关的兼容性问题吗?或者我需要使用与HTML5兼容的setInterval的类似方法?
发布于 2016-11-21 01:41:20
设置style.left时需要包括单位
theImage.style.left = xPosition + "px";
严格地说,这并不是HTML5的事情。只有在根本不包含文档类型的情况下,省略单元才有效:除非包含单元,否则包含诸如<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">之类的HTML4文档类型也会导致脚本失败。
(我在OS上的Safari、Chrome和Firefox的当前版本中测试了这一点;这三个版本的行为都是一样的。)
https://stackoverflow.com/questions/40707128
复制相似问题