sử dụng window.getComputedStyle
để có được những tính chiều rộng, sau đó tính toán để có được tỷ lệ phần trăm equvialent mà sẽ làm cho nó có cùng kích thước với chiều rộng.
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)+"%";
Lưu ý rằng phần tử neo sẽ lớn hơn so với chiều cao div khôn ngoan, để giữ nó bên cha mẹ bạn sẽ phải mở rộng nó xuống.
JSFiddle Demo
Nguồn
2013-09-22 17:27:48
Bạn có nghĩa là bạn muốn thay đổi kích thước tỷ lệ tương ứng? – Seazoux
Anh ta muốn chiều cao bằng với chiều rộng, khi chiều rộng là phần trăm. – Bart
Vâng, tôi có thể đặt chiều cao: tự động ... Nhưng tôi sẽ kiểm tra somethings ..: P – Seazoux