textarea中box-sizing
时间: 2023-10-01 21:12:23 浏览: 38
textarea 中的 box-sizing 属性用于设置元素的盒模型的计算方式。盒模型是指一个 HTML 元素的大小和边框的计算方式,包括元素的内容、内边距、边框和外边距。
box-sizing 属性有两个值可选:content-box 和 border-box。默认值为 content-box。
- content-box:元素的宽度和高度只包含内容的宽度和高度,不包括 padding、border 和 margin。
- border-box:元素的宽度和高度包含内容的宽度和高度,以及 padding 和 border 的宽度,但不包括 margin 的宽度。
在实际开发中,我们可以根据实际需求选择不同的计算方式。如果需要设置元素的宽度和高度时,希望包括 padding 和 border 的宽度,可以使用 border-box。如果需要设置元素的宽度和高度时,只考虑内容的宽度和高度,可以使用 content-box。
相关问题
修改代码:需要biaoge13内输入的文本自动换行且垂直,水平居中 .text{ top:0px !important; left:0px !important; width:100%; height:100%; position:absolute; resize: none; -webkit-box-sizing: border-box; /* <=iOS4, <= Android 2.3 */ -moz-box-sizing: border-box; /* FF1+ */ box-sizing: border-box; /* Chrome, IE10, Opera, Safari 5.1*/ border: solid; border-width: 4px; border-color: white; background-color: white; margin:0px; padding:0px; font-style: normal; text-align: center; } <td class="biaoge13"> <input class="text" type="text"> </td>
要实现文本自动换行且垂直水平居中,您可以使用CSS的一些属性和样式来修改代码。以下是修改后的代码:
```html
<style>
.text {
top: 0;
left: 0;
width: 100%;
height: 100%;
position: absolute;
resize: none;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
border: solid;
border-width: 4px;
border-color: white;
background-color: white;
margin: 0;
padding: 0;
font-style: normal;
text-align: center;
overflow-wrap: break-word; /* 自动换行 */
text-align: center; /* 水平居中 */
display: flex;
align-items: center; /* 垂直居中 */
justify-content: center; /* 水平居中 */
}
</style>
<td class="biaoge13">
<div class="text">
<textarea class="text" rows="4"></textarea>
</div>
</td>
```
在上面的代码中,我们将输入框由`<input>`改为`<textarea>`,以便实现文本的自动换行。然后,我们为包裹输入框的`<div>`添加了一些CSS样式,使其垂直和水平居中。通过`display: flex`和相关属性,我们可以轻松实现这些效果。
请注意,您可能需要根据您的页面布局和需求进一步调整和修改CSS样式。
获取光标在 textarea中 的 xy 坐标
在 textarea 中获取光标的 xy 坐标比较复杂,需要使用一些技巧。
以下是一种可能的实现方式:
```javascript
function getCaretCoordinates() {
var x = 0, y = 0;
var isFirefox = window.navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
if (isFirefox) {
// Firefox中需要将textarea的box-sizing设为border-box,否则会出现偏差。
var style = window.getComputedStyle(textarea, null);
x = style.getPropertyValue("padding-left").replace("px", "");
y = style.getPropertyValue("padding-top").replace("px", "");
}
if (typeof textarea.selectionStart == "number") {
var range = textarea.selectionRange;
var rect = textarea.getBoundingClientRect();
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
x = range.startOffset * (rect.width / textarea.value.length) + rect.left;
y = range.startOffset * (rect.width / textarea.value.length) + scrollTop + rect.top;
}
return { x: x, y: y };
}
```
这个函数先判断浏览器是否是 Firefox,如果是则需要将 textarea 的 box-sizing 设为 border-box,然后获取 textarea 的 padding-left 和 padding-top 值,用于之后的计算。
接着,判断 textarea.selectionStart 是否支持,如果支持则获取 textarea 的 selectionRange 和 getBoundingClientRect() 值,计算出光标的 x 和 y 坐标。最后返回一个包含 x 和 y 坐标的对象。