实现px和vw的转换

无聊才收藏 关注

收藏于 : 2022-08-08 09:43   被转藏 : 1   

1.实现效果

2.px,em,rem,vw,%,vm

1.px
px其实就是像素的意思,全称pixel,也就是图像的基本采样单位。对于不同的设备,它的图像基本单位是不同的,比如显示器和打印机。总的来说px就是对应我们显示器的分辨率。这样就会有个问题就是如果使用px的话我们就要根据不同电脑的分辨率来做自适应,有点麻烦。

2、em
em是相对长度单位。相对于当前对象内本文的字体尺寸(如果没有设置本文尺寸,那就是相对于浏览器默认的字体尺寸,也就是16px),这样计算的话。如果没有设置字体尺寸就是1em = 16px。如果使用em的话,有个好的建议,就是将body的font-size设置成62.5%,也就是16px * 62.5% = 10px。这样的话1em = 10px,方便我们计算。

3、rem
rem和em一样也是相对长度单位,但是不一样的是rem始终都是相对html根元素。这样有个很大的优点就是使用rem后不会受到对象内文本字体尺寸的影响,而且只需要改变根元素就能改变所有的字体大小。

4、vw和vh
vw和vh是视口(viewport units)单位,浏览器窗口的大小的单位,不受显示器分辨率的影响。但是没有最小设置。
css3新单位,view width的简写,是指可视窗口的宽度。假如宽度是1800px的话。那10vw就是180px
举个例子:浏览器宽度1800px, 1 vw = 1800px/100 = 18 px。

5.%
一般来说就是相对于父元素的,对于普通定位元素就是我们理解的父元素,对于position: absolute;的元素是相对于已定位的父元素,对于position: fixed;的元素是相对于ViewPort(可视窗口)。

6.vm
css3新单位,相对于视口的宽度或高度中较小的那个。如:浏览器高度1000px,宽度1800px,取最小的浏览器高度,1 vm = 100px/100 = 10px。

3.代码

                    
                      <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title></title>
	<style>
		input{
			background:none;  
			outline:none;  
			border:none;
		}
		.cen{
			width: 500px;
			height: 400px;
			margin: auto;
			/* 垂直居中 */
			position:absolute;
			left:0;
			top: 0;
			bottom: 0;
			right: 0;
			font-size: 30px;
		}
		.i_view{
			width: 330px;
			margin-right: 10px;
			height:  80px;
			line-height: 80px;
			padding-left:  20px;
			font-size: 30px;
			border: 1px solid #ccc;
			border-radius: 20px;
			margin-bottom: 20px;
		}
		.cen input::-webkit-input-placeholder {
			color:#ccc;
			font-size: 20px;
			text-align: left;
		}
		button{
			border: none;
			background-color: transparent;
			outline: none;
		}
			
		.btn{
			width: 80px;
			height: 40px;
			line-height: 40px;
			text-align: center;
			border-radius: 20px;
			border: 1px solid #7FCFF7;
			background-color: #7FCFF7;
			color: #fff;
			margin-bottom: 20px;
		}
		.mb{
			margin-bottom: 10px;
		}
	</style>
</head>
<body>
	<div >
		<input id="value" type="text" placeholder="请输入" />px
		<button onclick="change()" >转换</button>
		<div id="value0" ></div>
		<div id="value1"></div>
	</div>
    
</body>
</html>
<script>
    function change(){
        let widthVal = Number(document.getElementById('value').value);
        let nowVW = widthVal/(1920/100);
		let nowVH = widthVal/(1080/100);
        document.getElementById('value0').innerText = 'vw结果:'+nowVW.toFixed(2)+'vw';
		document.getElementById('value1').innerText = 'vh结果:'+nowVH.toFixed(2)+'vh';
    }

</script>

                    
                  
 阅读文章全部内容  
点击查看
文章点评
相关文章
无聊才收藏 关注

文章收藏:17

TA的最新收藏