document 和 window.document

DOM访问差异详解
本文通过实验对比了在不同浏览器环境下,使用document、window.document及window.parent.document获取元素的区别。通过具体的HTML示例代码展示了这些方法如何针对不同上下文中的元素进行操作。

今天看讲document 和 window.document区别的文章,自己测试了I8+和chrome,document 和window.document都指向了同一个对象,而window.document和window.parent.document是指向不同的对象。window.document指向当前文档对象,window.parent.document指向父窗体的当前文档对象

现放上代码:

main.html

<!DOCTYPE HTML>
<html>
	<head>
		<title>main</title>
	</head>
	<body>
		<input id='input1' type='text' name='name1' value='input1' />
		<iframe src='sub.html' > </iframe>
	</body>
</html>

sub.html

<!DOCTYPE HTML>
<html>
	<head>
		<title>sub</title>
	</head>
	<script type="text/javascript">
		function showA() {
			alert(document.getElementById('input2').value);
		}

		function showB() {
			alert(window.document.getElementById('input2').value);
		}
		
		function showC() {
			alert(window.parent.document.getElementById('input1').value);
		}
	</script>
	<body>
		<input id='input2' type='text' name='name2' value='input2' />
		
		<input type='button' name='but1' value='showA()' onclick='javascript:showA();' />
		
		<input type='button' name='but2' value='showB()' onclick='javascript:showB();' />
		
		<input type='button' name='but3' value='showC()' onclick='javascript:showC();' />
		
	</body>
</html>


### window.innerWidth 与 document.documentElement.clientWidth 的区别 `window.innerWidth` `document.documentElement.clientWidth` 都可以用来获取浏览器窗口的宽度,但它们之间存在一些关键的区别: - `window.innerWidth` 返回的是包括滚动条在内的整个视口的宽度[^2]。这意味着如果浏览器显示了垂直滚动条,`window.innerWidth` 的值会包含滚动条的宽度。 - `document.documentElement.clientWidth` 返回的是不包括滚动条在内的文档可见区域的宽度[^3]。因此,当页面存在滚动条时,`document.documentElement.clientWidth` 的值通常会比 `window.innerWidth` 小。 #### 示例代码 以下是一个简单的示例,用于演示两者的差异: ```javascript // 包含滚动条的宽度 var widthWithScrollbar = window.innerWidth; // 不包含滚动条的宽度 var widthWithoutScrollbar = document.documentElement.clientWidth; console.log("包含滚动条的宽度: " + widthWithScrollbar); console.log("不包含滚动条的宽度: " + widthWithoutScrollbar); ``` 在某些情况下,例如需要调整元素的布局或进行响应式设计时,选择使用 `window.innerWidth` 还是 `document.documentElement.clientWidth` 取决于是否需要考虑滚动条的影响。 #### 兼容性问题 需要注意的是,在旧版浏览器中(如 IE8 及以下),`document.documentElement.clientWidth` 的支持可能存在问题,此时可以使用 `document.body.clientWidth` 作为替代方案[^4]。然而,现代浏览器普遍支持 `document.documentElement.clientWidth`,因此在这种环境下可以直接使用它。 此外,`window.innerWidth` 在所有现代浏览器中都得到了良好的支持,但在某些特定场景下可能会遇到兼容性问题[^5]。 ### 总结 - `window.innerWidth` 包括滚动条宽度。 - `document.documentElement.clientWidth` 不包括滚动条宽度。 - 在需要精确计算可视区域大小时,应根据具体需求选择合适的属性。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值