如何用JavaScript的.getBoundingClientRect将首图宽高应用到其余图片?
问题:首图宽高仅能应用到第二张图片,后续图片不生效的解决方法
我尝试将第一张图片的宽度和高度应用到后续所有图片中。目前已成功将首图宽高应用到第二张图片,但无法应用到第三张、第四张及更多图片。我是JavaScript新手,可能犯了低级错误。
我的代码如下:
HTML
<div class="boxA"> <img class="landscape"src="http://placekitten.com/800/400"> </div> <div class="boxB"> <img class="portrait"src="http://placekitten.com/400/800"> </div> <div class="boxB"> <img class="portrait"src="http://placekitten.com/400/800"> </div>
CSS
.boxA { width: 20%; border: solid blue; display: block; float: left; } .boxB { border: solid blue; display: block; float: left; } .landscape { width: 100%; display: block; } .portrait { height: 100%; /** to center horizontally **/ margin: auto; display: block; }
JavaScript
var boxA = document.querySelector(".boxA"), boxB = document.querySelector(".boxB") function copyHeight(from,to){ to.style.height = from.getBoundingClientRect().height + "px" } copyHeight(boxA,boxB) function copyWidth(from,to){ to.style.width = from.getBoundingClientRect().width + "px" } copyWidth(boxA,boxB)
问题原因
document.querySelector(".boxB")只会返回页面中第一个匹配.boxB类名的元素,第三张及以后的.boxB元素根本没被选中,自然不会应用宽高。
解决方法
改用document.querySelectorAll(".boxB")获取所有.boxB元素,得到元素集合后遍历每个元素,单独调用复制宽高的函数:
修改后的JavaScript代码:
var boxA = document.querySelector(".boxA"), boxBs = document.querySelectorAll(".boxB") function copyHeight(from,to){ to.style.height = from.getBoundingClientRect().height + "px" } function copyWidth(from,to){ to.style.width = from.getBoundingClientRect().width + "px" } // 遍历所有boxB元素,逐个应用宽高 boxBs.forEach(function(boxB) { copyHeight(boxA, boxB) copyWidth(boxA, boxB) })
额外说明
querySelectorAll返回的是类似数组的NodeList,现代浏览器可直接用forEach遍历;若需兼容旧浏览器,可改用for循环- 建议在图片加载完成后再执行宽高复制,避免图片未加载导致宽高获取不准确,可将代码放入
window.onload事件或给图片添加load监听
内容的提问来源于stack exchange,提问作者Gbol
相关产品推荐
相关产品推荐

