【问题标题】:Javascripts not working when <!doctype html> inserted in correct format当 <!doctype html> 以正确的格式插入时,Javascript 不起作用
【发布时间】:2012-07-08 05:15:21
【问题描述】:

我正在开发一个网页并在页面上使用一些 javascripts 来移动一些 html 元素,但是我发现当 &lt;!doctype html&gt; 时 javascript 代码不起作用 或任何类型的 &lt;!doctype&gt; 添加到页面顶部!这是什么错误?

我在 google 上搜索,我发现 &lt;!doctype html&gt; 是正确的格式,即使 stackoverflow 源代码也有它,但是当我使用它时,javascripts 无法正常工作,但当它删除脚本工作正常并且 html 对象正在移动但我的样式消失了,因为删除&lt;!doctype html&gt;

<!doctype html>   when this line removed it works(html element is moving)
<html>
<head>
    <script type="text/javascript">

        function scrollDiv(){
                  var obj = document.getElementById("movingDiv");
                  obj.style.left = 100;
                  obj.style.top = 10;
                  }

                document.onclick = scrollDiv;

    </script>
</head>
<body  class="body">
<div class="maindiv" id="mainDiv">
  <div class="html_js_code" style="text-align:center;">

  <div id="movingDiv" style="position:absolute;left:100pt;top:10pt;border:1px blue 

outset;width:160px;background-color:lightyellow;font-weight:bold;">Moving Div</div>
</div>
</div>
</body>
</html>

【问题讨论】:

  • 你的逻辑,你的思维方式很好。只有结论是错误的:错误必须在您的 Javascript 代码中。

标签: javascript html


【解决方案1】:

如果没有文档类型,浏览器会假定未标记的长度以像素为单位。对于 doctype,它们需要一个明确的单位。

obj.style.left = "100px";
obj.style.top = "10px";

【讨论】:

  • 是的,它有效!多谢,伙计。所以每次附带doctype时我都必须使用像素对吗?非常感谢你。
  • @NaveenChamikaraGamage 你总是必须在适当的时候使用像素。但是当你不指定 doctype 时,浏览器会更宽松。
  • 我脑子里还有一个问题,我不能在使用这个文档类型时将 body with 和 height 设置为 90% 吗?
【解决方案2】:

你也忘了把括号放在你调用的函数的末尾。我也很确定你错误地通过了它。我相信它应该是这样的:

document.onclick = scrollDiv();

document.onclick(scrollDiv());

【讨论】:

  • 不,它不应该是这样的。请尝试一下。
猜你喜欢
  • 2022-07-06
  • 2018-02-18
  • 1970-01-01
  • 1970-01-01
  • 2021-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多