如何使<输入类型= 比 "text" ><span>宽 2em



我的HTML中有一个<span>元素,它可以通过javascript更改其内容。但是,出于样式目的,我希望我上面的<input type="text">始终保持2em宽。我不介意使用JQuery。

提前感谢!

编辑:我尝试过的事情:

$( document ).ready(function() {
var tips = document.getElementById('usageTip');
var name = document.getElementById('name');
name.setAttribute("width", tips.style.width.valueOf + 2);
});
$( document ).ready(function() {
var tips = document.getElementById('usageTip');
var name = document.getElementById('name');
name.setAttribute("width", tips.style.width.value + 2);
});
$( document ).ready(function() {
var tips = document.getElementById('usageTip');
var name = document.getElementById('name');
name.setAttribute("width", tips.style.width);
});
$( document ).ready(function() {
var tips = document.getElementById('usageTip');
var name = document.getElementById('name');
name.setAttribute("width", tips.width + 2);
});

请记住,CSS 将name输入框的宽度指定为width:20em;并且未指定tips范围(自动(。

没有Jquery演示,你的意思是这个吗?

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Demo</title>
</head>
<body>
	<style>
		.box_wrap {
			display: inline-block;
			box-sizing: border-box;
			padding:2rem;
			background: #f0f0f0;
		}
		.box {
			outline: none;
		}
	</style>
<span class="box_wrap">
<input type="text" id="box" class="box"/>
</span>
<script>
	var input = document.querySelector("#box");
	var widht = 20;
input.style.width = widht + "em";
</script>
</body>
</html>

使用 jquery 你可以做到:

$('#name').css( "width", "calc("+$("#usageTip").width()+"px + 2em)" );

$(document).ready(function() {
$('#resize').click(function() {
$('#inp').css( "width", "calc("+$("#sp").width()+"px + 2em)" );
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span style="background:#faa" id="sp">Content of the span</span>
<br/>
<input type="text" id="inp">
<br/>
<input type="button" id="resize" value="resize" />

最新更新