offsetHeight在OnLoad中为0的现象

在使用IE中,特别在目前div+css的方式,往往不定义div的高度,这是在添加div内容后,需要获取div的高度时,往往需要用到offsetHeight。

在使用中,有时会碰到offsetHeight获取到为0的现象,但如果你用各种JS调试工具调试,又能在对象中看到值(如果直接指向offsetHeight是没值的,但如果是对象查看是有值的,在调试器中回车查看对象就已经刷新对象了,所以有值。)

比如下面片段

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
	<script language='javascript'>
		window.attachEvent( "onload", function(){ _resizeScroll2();} );
		window.onresize=function(){winresize();};
		function _resizeScroll2(){
			 var html1 = '<div id="divcj" style="margin-top:15px;font-size:10px;width:400px;">'
		     + '<div style="float:left;width:50px;">测试</div>'
		   	 + '<div style="float:left;width:320px;">danielinbiti</div>'
  		   + '</div>'
  		   + '<div id="divcj2" style="margin-top:15px;font-size:10px;width:400px;">'
		   	 + '<div style="width:320px;">danielinbiti</div>'
  		   + '</div>'
			 document.getElementById('outer').innerHTML=html1;
			 document.getElementById('divcj2').style.display='none';
			 alert(document.getElementById('divcj2').offsetHeight);
		}
  </script>
</head>
<body>
	<div id='outer'></div>
</body>
</html>

如果获取divcj的高度,那么在onload中获取到的是0。因为divcj下有float方式布局的。

这时如果div简单,可以借助隐藏层,比如这里的divcj2,把float去掉后,获取到的高度和divcj一样高。

<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>-</title> <style> body { margin: 0; padding: 0; overflow: hidden; } .container { position: relative; display: flex; width: 1920px; height: 900px; overflow: hidden; cursor: pointer; top:220px; } .box { position: absolute; width: 500px; white-space: nowrap; /* left: 0; */ text-align: center; /* 让内容居中 */ } .image-container { /* border: 1px solid #ddd; */ border-radius: 4px; padding: 5px; text-align: center; transition: transform 0.3s; } .image-container img { max-width: 100%; height: auto; max-height: 150px; } .loading { text-align: center; font-size: 18px; color: #666; margin: 20px 0; } .bg { width: 1920px; height: 1080px; background-image: url(img/bg.jpg); } </style> </head> <body> <div class="bg"> <div id="loading" class="loading">正在加载图片...</div> <div class="container" id="container"></div> <div style="float: right; margin-right: 100px;margin-top: 20px; position: relative;z-index: 999;"> <a href="index.html"><img style="" src="img/btn1.png" alt="" /></a> <a href="qianzi.html"><img style="" src="img/btn2.png" alt="" /></a> </div> </div> <script> document.addEventListener('DOMContentLoaded', function () { const container = document.getElementById('container'); const loadingElement = document.getElementById('loading'); fetch('images/') .then(response => { if (!response.ok) { throw new Error(`目录请求失败,状态码:${response.status}`); } return response.text(); }) .then(html => { const parser = new DOMParser(); const doc = parser.parseFromString(html, 'text/html'); const links = doc.querySelectorAll('a[href]'); const imageFiles = Array.from(links) .map(link => link.getAttribute('href')) .filter(file => /\.(jpg|jpeg|png|gif|webp)$/i.test(file)); if (imageFiles.length === 0) { loadingElement.textContent = '未找到图片文件'; return; } loadingElement.style.display = 'none'; // 动态创建box,每个box一个图片 const boxWidth = 400; const boxHeight = 200; // 估算高度,图片150 + padding + border + margin,实际可根据需要调整 const gapX = 0; // 列间距 const gapY = 50; // 行间距 const boxesPerColumn = 3; imageFiles.forEach((file, index) => { const box = document.createElement('div'); box.className = 'box'; // 计算列号和行号 const col = Math.floor(index / boxesPerColumn); const row = index % boxesPerColumn; // 设置left和top box.style.left = `${col * (boxWidth + gapX)}px`; box.style.top = `${row * (boxHeight + gapY)}px`; const imageContainer = document.createElement('div'); imageContainer.className = 'image-container'; const img = document.createElement('img'); img.src =file; imageContainer.appendChild(img); box.appendChild(imageContainer); container.appendChild(box); }); // 动画逻辑 const boxes = document.getElementsByClassName('box'); function moveBox(element, delay, distance) { setTimeout(() => { // 开始平滑移动 element.style.transition = 'transform 30s linear'; element.style.transform = `translateX(-${distance}px)`; // 20秒后,取消动画,瞬间回到起点 setTimeout(() => { element.style.transition = 'none'; element.style.transform = 'translateX(0)'; // 强制浏览器渲染,触发重绘 element.offsetHeight; // 读取offsetHeight强制重绘 // 重新开始动画 moveBox(element, 0, distance); }, 20000); }, delay); } // 给每行box设置不同的延迟,避免同移动 // 计算移动距离 const totalColumns = Math.ceil(imageFiles.length / boxesPerColumn); const containerWidth = 1920; const totalWidth = totalColumns * (boxWidth + gapX); const distance = containerWidth + totalWidth; Array.from(boxes).forEach((box, idx) => { if(idx%3==0){ moveBox(box, 1900, distance);//控制第一行延迟 }else if((idx+1)%3==0){ moveBox(box, 1400, distance);//控制第三行延迟 }else{ moveBox(box, 1100, distance);//控制第二行延迟 } }); }) .catch(error => { console.error('获取图片失败:', error); loadingElement.textContent = '加载图片失败,请确保通过本地服务器运行此页面'; }); }); </script> </body> </html> 这个是我的图片动效代码,我现在需要不改变代码获取图片方式的前提下,让代码的循环更加流畅丝滑
最新发布
06-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值