Javascript-使用Doctype让scrollTop返回0,为什么?

当我将此Doctype放入文档document.body.scrollTop返回零.

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

这是为什么?

解决方法:

使用该Doctype时,会将当前的所有浏览器都放在所谓的Almost Standards mode中,如果没有它,您将处于Quirks模式.

正如您在this page上所读到的,

[m]ost browsers provide window.pageXOffset/pageYOffset. These are completely reliable. Once again, Internet Explorer is the odd one out, as it does not provide these properties. Internet Explorer and some other browsers will provide document.body.scrollLeft/Top. In strict mode, IE 6 and a few other browsers, provide document.documentElement.scrollLeft/Top.

那里提供的脚本计算所需的值:

function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

另一个有趣的文章出现在QuirksMode,A tale of two viewports上.

上一篇:声明DOCTYPE时,Javascript在Chrome中无效


下一篇:使用DOCTYPE时使用JavaScript设置样式的怪异问题