求解原生js碰到必须在页面底部引用JS文件才有效的问题
<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();