求解原生js碰到必须在页面底部引用JS文件才有效的问题

qq_36509661 2017-01-13 02:41:09
<div class="big-pic-box">
<img src="images/cleaning.jpg" alt="" class="big-pic">
<div class="wordbox">
<div>清洁服务专员</div>
<div>用细节说话,为你提供整洁清新的安全感</div>
<div><button class="btnmd">预定布草换洗</button></div>
</div>
</div>
<script type="text/javascript" src="js.js"></script>
目的是获得图片的高度和内容DIV的高度,控制下面内容DIV垂直居中
问题1:JS要在页面底部引用才有效,否则就获取不到class了,加上window.onload=function(){}也是一样要放页面底部。
问题2:我在其他页面也引用了这个JS文件,其他页面没有wordbox这个class名,然后就一直报错,JS找不到这个class名,以前用jquery的时候可以加个判断class的length来处理,原生JS试了下貌似没用
function wordbox(){
var boxheight=document.querySelector(".wordbox").offsetHeight;
var imgheight=document.querySelector(".big-pic").offsetHeight;
var newheight=(imgheight-boxheight)/2+'px';
document.querySelector(".wordbox").style.top=newheight;
}
wordbox();
...全文
167 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
引用 4 楼 qq_36509661 的回复:
试了下window.onload=function(){} 要直接写里面才可以 window.onload=function(){ var boxheight=document.querySelector(".wordbox").offsetHeight; var bigheight=document.querySelector(".big-pic").offsetHeight; var newheight=(bigheight-boxheight)/2+'px'; document.querySelector(".wordbox").style.top=newheight; } 如果我这样写就不行了 window.onload=function(){ wordbox(); } function wordbox(){ var boxheight=document.querySelector(".wordbox").offsetHeight; var imgheight=document.querySelector(".big-pic").offsetHeight; var newheight=(imgheight-boxheight)/2+'px'; document.querySelector(".wordbox").style.top=newheight; }
楼主再找找问题看 逻辑上 你这样写是没问题的 wordbox函数里的代码块是会等到页面dom和图片都加载完全后执行
qq_36509661 2017-01-13
  • 打赏
  • 举报
回复
试了下window.onload=function(){} 要直接写里面才可以 window.onload=function(){ var boxheight=document.querySelector(".wordbox").offsetHeight; var bigheight=document.querySelector(".big-pic").offsetHeight; var newheight=(bigheight-boxheight)/2+'px'; document.querySelector(".wordbox").style.top=newheight; } 如果我这样写就不行了 window.onload=function(){ wordbox(); } function wordbox(){ var boxheight=document.querySelector(".wordbox").offsetHeight; var imgheight=document.querySelector(".big-pic").offsetHeight; var newheight=(imgheight-boxheight)/2+'px'; document.querySelector(".wordbox").style.top=newheight; }
天际的海浪 2017-01-13
  • 打赏
  • 举报
回复
原生的直接判断 if (document.querySelector(".wordbox")) { .wordbox存在 } else { .wordbox不存在 }
二月十六 2017-01-13
  • 打赏
  • 举报
回复
1、有加载顺序问题,必须在页面加载完之后才能获取到对象。 2、提倡js代码放到页面的最下边(除了需要在dom加载前加载 比如微信授权的js),防止页面阻塞等问题。 3、如果想写在页面前边,可以写在window.onload里,当文档加载完成之后就会触发该事件。
当作看不见 2017-01-13
  • 打赏
  • 举报
回复
由于是顺序执行的,在页面头部 ,html 的dom 还没有加载。获取不到对象,所以无效。 想放在头部 可以 window.onload=function(){ 你的代码 }

87,914

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧