代码在以下情况下不起作用:<!DOCTYPE html>顶部

Code Does Not Work WIth <!DOCTYPE html> at the top

本文关键字:DOCTYPE html gt 顶部 lt 情况下 不起作用 代码      更新时间:2023-09-26

我的页面顶部有<!DOCTYPE html>,该页面应该允许用户单击页面上的任何位置,然后重定向到另一个URL。

当我删除<!DOCTYPE html时它可以工作,但我想将其保留在页面中

这是代码:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
    BODY.enterPage{
      cursor:hand;
    }
</style>
<script>
  function goto(){
    location.href = "http://www.google.com"
  }
</script>
</head>
  <body class="enterPage" onclick="goto();">
  Your Content
</body>
</html>

为什么会发生这种情况?

欣赏@Pointy评论,此外,在CSS中做以下更改:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Untitled Document</title>
        <style>
            body.enterPage {
                cursor: pointer;             //Not hand!
            }
            html, body {                     //Set document width/height to 100%
                width: 100%;
                height: 100%;
            }
        </style>
        <script>
            function goto() {
                location.href = "http://www.google.com"
            }
        </script>
    </head>
    <body class="enterPage" onclick="goto();">
        Your Content
    </body>
</html>

将主体的高度和宽度添加到100%。很可能它可以解决这个问题。

要修复功能问题,使整个区域都可以点击,唯一需要的就是设置

html, body { height: 100%; }

然而,这仍然会在边缘留下小区域(几像素的边距),所以如果你真的想让整个视口都可以点击,可以添加

html, body { margin: 0; padding: 0; }

原因是在"标准模式"中,默认情况下,浏览器会使body元素的高度与其内容所需的高度一样(通过在其上设置边框可以看到)。当缺少doctype字符串时,浏览器会在"怪癖模式"下运行,在这种模式下会发生奇怪的事情,包括模仿旧浏览器,默认情况下会使body 100%高。当你想在"标准模式"中这样做时,只需在CSS中说出来。

要使指针(在CSS中错误地命名为cursor)在所有浏览器上看起来像一只手或类似的图标,请添加

body { cursor: hand; cursor: pointer; }

这既可以处理非常旧的IE版本(可以识别hand,但不能识别pointer),也可以处理正确实现cursor的现代浏览器。