em 和 px相互转换

时间:2021-08-08 19:59:35
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
function convert (id) {
var px_val = document.getElementById('pxToEm').value,
em_val = document.getElementById('emToPX').value,
base_val = document.getElementById('basePX').value;
if(!base_val){
document.getElementById('tip').value = '基本单位不能为空';
return;
}else{
document.getElementById('tip').value = '';
}
base_val = base_val.replace(/[^0-9.]/g, '');
if(id === 'PXtoEMConvert'){
if(!px_val){
document.getElementById('tip').value = 'PX to EM不能为空';
return;
}
px_val = px_val.replace(/[^0-9.]/g, '');
document.getElementById('tip').value = '';
document.getElementById('result').value=((px_val / base_val).toFixed(3) + 'em');
}else if(id === 'EMtoPXConvert'){
if(!em_val){
document.getElementById('tip').value = 'EM to PX不能为空';
return ;
}
em_val = em_val.replace(/[^0-9.]/g, '');
document.getElementById('tip').value = '';
document.getElementById('result').value=(parseInt(em_val * base_val) + 'px');
}
}
</script>
</head>
<body>
<img src="px_em.png" alt="px和em单位相互转换">
<br>
<label for="basePx">基本单位:</label>
<input type="number" id="basePX">px
<br>
<label for="pxToEm">PX to EM:</label>
<input type="number" id="pxToEm">px
<br>
<label for="emToPX">EM to PX:</label>
<input type="number" id="emToPX">em
<br>
<label for="result">转换结果:</label>
<input type="text" id="result">
<br>
<input type="button" id="PXtoEMConvert" onclick="convert(this.id)" value="PX to EM转换">
<input type="button" id="EMtoPXConvert" onclick="convert(this.id)" value="EM to PX转换">
<br>
<label for="tip">提示:</label>
<input type="text" id="tip" readonly>
</body>
</html>
相关文章链接:
http://www.cnblogs.com/leejersey/p/3662612.html