用于window.getComputedStyle
获取计算出的宽度,然后进行计算以获得等效百分比,使其与宽度相同。
HTML
<div class="someDiv" style="width:900px;height:200px;">
<a class="someAnchor" style="display:block; float:left; width:35%; background:green"></a>
</div>
JS
var anchor = document.querySelector(".someDiv .someAnchor");
var astyle = window.getComputedStyle(anchor);
anchor.style.height = astyle.width; //this will make it static though
//to make it a percentage like width so it will expand and contract with resize of parent element
var pstyle = window.getComputedStyle(anchor.parentNode);
var pheight = parseInt(pstyle.height);
var awidth = parseInt(astyle.width);
anchor.style.height = ((awidth/pheight)*100)+"%";
请注意,锚元素将大于 div 高度,要将其保留在父元素中,您必须将其缩小。
JSFiddle 演示