Giải pháp của tôi tạo biến CSS thể hiện chiều cao của vùng chứa tương ứng với chế độ xem, trong đơn vị "vh", biến này sau đó có thể được sử dụng với hàm "calc" CSS3 để tính chiều cao của phông chữ theo phần trăm của chiều cao của container.
kích thước của container được đo mỗi khi khung nhìn (cửa sổ) được thay đổi kích cỡ
<html>
<head>
<style>
.container {
width:100%;
/*
any rules you like to set the dimensions of the container
*/
top:40px;
height:30vh;
border:1px solid red;
white-space:nowrap;
}
</style>
<script>
function setCSSVariableAccordingToElementHeightRelativeToViewPort(elementClassName, cssVariableName, immutableElement)
{
var element
/*
the "immutableElement" parameter is
true when the container is never recreated,
false if its generated dynamicaly
*/
if(immutableElement === true) {
element = document.querySelector("." + elementClassName)
}
var onResize = function() {
if(immutableElement !== true) {
element = document.querySelector("." + elementClassName)
}
if(element != undefined) {
var elementHeight = element.offsetHeight
var elementVH = (elementHeight/window.innerHeight) * 100
element.style.setProperty(cssVariableName, elementVH + "vh")
}
}
onResize()
window.onresize = onResize
}
</script>
</head>
<body>
<div class="container">
<span style="font-size:calc(var(--container-vh) * 0.25)">25%</span>
<span style="font-size:calc(var(--container-vh) * 0.50)">50%</span>
<span style="font-size:calc(var(--container-vh) * 1.00)">100%</span>
</div>
</body>
<script>
setCSSVariableAccordingToElementHeightRelativeToViewPort("container", "--container-vh", true)
</script>
</html>
JSFiddle
Nguồn
2017-04-19 23:33:58
ohh - đẹp quá. kiểm tra xem nó hoạt động như thế nào. – circusdei
có vẻ tốt với tôi - cảm ơn vì liên kết! Bây giờ lên hình nền:/ – circusdei