[英]Change an element width in px when resizing the window
How can I change an element with a fixed width in px when i resize the window?当我调整窗口大小时,如何以 px 为单位更改具有固定宽度的元素? I need to use an absolute unit, i can not use relative units like % or vw.Every time the window is resized with 1 px i need to decrease the element width by 0.2px.
我需要使用绝对单位,我不能使用像 % 或 vw 这样的相对单位。每次将窗口大小调整为 1 像素时,我都需要将元素宽度减少 0.2 像素。
I tried to use the window
resize eventListener but i don't know what calculations needs to be done.我尝试使用
window
调整大小事件侦听器,但我不知道需要进行哪些计算。
What you want can be achieved by using javascript.你想要的可以通过使用 javascript 来实现。 I've created a logic to do that :
我已经创建了一个逻辑来做到这一点:
<script>
function myFunction() {
var initialscreenwidth = window.innerWidth; //Set Initial Screen Width
setInterval(function() { //looping the script
var screenwidth = window.innerWidth;
var difference = initialscreenwidth - screenwidth; //Calculating the change in screen-size
if (difference != 0) { //Checking if there is a change in width
var element = document.getElementById('demo');
var style = window.getComputedStyle(element, null).getPropertyValue('font-size'); //Getting default font-size of the element
var initialfontsize = parseFloat(style);
var fontdifference = -(parseFloat(difference) / 5); //1px change in screen-size = 0.2px change in font-size
var newfontsize = initialfontsize + fontdifference;
var newfontsizepx = newfontsize + "px";
if (newfontsize > 1) {
document.getElementById("demo").style.fontSize = newfontsizepx;
}
}
initialscreenwidth = window.innerWidth;
}, 300); //reloads in every 300ms
}
myFunction();
</script>
Paste this at the end of your body section, somehow using this in the head section is not working.将其粘贴到正文部分的末尾,不知何故在头部部分使用它不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.