获取光标在 textarea中 的 xy 坐标
时间: 2024-03-10 12:44:55 浏览: 30
在 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 坐标的对象。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)