Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/377.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用JavaScript查找输入和文本区域插入符号位置坐标?_Javascript_Html_Coordinates_Caret_Getcaretpos - Fatal编程技术网

如何使用JavaScript查找输入和文本区域插入符号位置坐标?

如何使用JavaScript查找输入和文本区域插入符号位置坐标?,javascript,html,coordinates,caret,getcaretpos,Javascript,Html,Coordinates,Caret,Getcaretpos,我试图在JavaScript函数(如onkeydown,onkeypress,onkeypup等)的类型为text的TextArea或Input中找出相对于文档(整个网页)的插入符号位置坐标 为此,我创建了下面的HTML <input dir="rtl" type="text" id="TEST_INPUT" onkeydown="myFunction(this)"></input> <textarea dir="rtl" id="TEST_TEXTAREA" on

我试图在JavaScript函数(如
onkeydown
onkeypress
onkeypup
等)的类型为text的
TextArea
Input
中找出相对于文档(整个网页)的插入符号位置坐标

为此,我创建了下面的HTML

<input dir="rtl" type="text" id="TEST_INPUT" onkeydown="myFunction(this)"></input>
<textarea dir="rtl" id="TEST_TEXTAREA" onkeyup="myFunction(this)"></textarea>

并运行下面的JavaScript

<script type="text/javascript">
/* Main Function
----------------------------------------------- */
function myFunction(Desired_ID){
    // Extra Codes Here ETC...
    document.getElementById(Desired_ID.id).style.backgroundColor = "red";
    // Extra Codes Here ETC...
    var coords = getSelectionCoords(Desired_ID);
    alert(coords.left + ", " + coords.top);
    // Extra Codes Here ETC...
}

/* Get Caret XY Coordinate
----------------------------------------------- */
function getSelectionCoords(Desired_ELEMENT) {
// ------>>> What To Do Here Is The Problem To Cover All Browsers <<<------
return {left:x,top:y};
}
</script>

/*主要功能
----------------------------------------------- */
函数myFunction(所需的\u ID){
//这里有额外的代码等等。。。
document.getElementById(所需的ID.ID).style.backgroundColor=“红色”;
//这里有额外的代码等等。。。
var coords=getSelectionCoords(所需的_ID);
警报(coords.left+”,“+coords.top);
//这里有额外的代码等等。。。
}
/*获取插入符号XY坐标
----------------------------------------------- */
函数getSelectionCoords(所需元素){

//------>>>这里要做的是覆盖所有浏览器的问题在不断工作和尝试之后,我找到了我想要的答案,在这里我以代码的形式在下面分享它,您也可以在下面的


/*主要功能
----------------------------------------------- */
函数myFunction(所需的\u ID){
//这里有额外的代码等等。。。
document.getElementById(所需的ID.ID).style.backgroundColor=“红色”;
//这里有额外的代码等等。。。
var坐标=getCaretCoordinates(所需的_ID、所需的_ID.selectionStart);
警报(coordinates.left+“,”+coordinates.top);
//这里有额外的代码等等。。。
}
/*获取插入符号XY坐标
----------------------------------------------- */
/*jshint浏览器:true*/
(功能(){
//我们复制到镜像div中的属性。
//请注意,有些浏览器,如Firefox,
//不要连接属性,即填充顶部、底部等->填充,
//因此,我们必须具体地处理每一个属性。
变量属性=[
'方向',//RTL支持
“盒子大小”,
'width',//在Chrome和IE上,不包括滚动条,因此镜像div的包装方式与textarea完全相同
“高度”,
“溢出x”,
'overflowY',//复制IE的滚动条
“borderTopWidth”,
“borderRightWidth”,
“borderBottomWidth”,
“borderLeftWidth”,
“边界样式”,
“paddingTop”,
“paddingRight”,
"垫底",,
“paddingLeft”,
// https://developer.mozilla.org/en-US/docs/Web/CSS/font
“fontStyle”,
"字体变体",,
“fontWeight”,
“fontStretch”,
“字体大小”,
“FontSizedJust”,
“线宽”,
“丰特家族”,
“textAlign”,
“文本转换”,
“文本缩进”,
“textDecoration”,//可能没什么区别,但最好是安全的
“字母间距”,
“字间距”,
“tabSize”,
“莫扎布尺寸”
];
var isBrowser=(窗口的类型!=‘未定义’);
var isFirefox=(isBrowser&&window.mozInnerScreenX!=null);
功能getCaretCoordinates(元素、位置、选项){
如果(!isBrowser){
抛出新错误(“textarea-caret-position#getCaretCoordinates应仅在浏览器中调用”);
}
var debug=options&&options.debug | | false;
如果(调试){
var el=document.querySelector(“#输入文本区域插入符号位置镜像div”);
if(el){el.parentNode.removeChild(el);}
}
//镜像div
var div=document.createElement('div');
div.id='输入文本区域插入符号位置镜像div';
文件.正文.附件(div);
var style=div.style;
var computed=window.getComputedStyle?getComputedStyle(元素):element.currentStyle;//IE的currentStyle<9
//默认文本区域样式
style.whiteSpace='pre-wrap';
if(element.nodeName!==“输入”)
style.wordWrap='break word';//仅适用于textarea-s
//屏幕外定位
style.position='absolute';//需要正确返回坐标
如果(!调试)
style.visibility='hidden';//不是'display:none',因为我们需要渲染
//将元素的属性传输到div
properties.forEach(函数(prop){
样式[prop]=计算的[prop];
});
如果(iFirefox){
//Firefox对textareas的溢出属性撒谎:https://bugzilla.mozilla.org/show_bug.cgi?id=984275
if(element.scrollHeight>parseInt(computed.height))
style.overflowY='scroll';
}否则{
style.overflow='hidden';//使Chrome不呈现滚动条;IE保持overflowY='scroll'
}
div.textContent=element.value.substring(0,位置);
//输入type=“text”与textarea:space的第二个特殊处理需要用非中断空格替换-http://stackoverflow.com/a/13402035/1269037
if(element.nodeName==='INPUT')
div.textContent=div.textContent.replace(/\s/g,“\u00a0”);
var span=document.createElement('span');
//包装必须完全复制*,包括长单词被复制时
//转到下一行,在(#7)之前的行末尾有空格。
//要做到这一点,唯一可靠的方法是复制文件的其余部分
//textarea的内容放入在插入符号位置创建的文本中。
//对于输入,只要“.”就足够了,但为什么要麻烦呢?
span.textContent=element.value.substring(位置)| |'。;/| | |,因为完全空的人造span根本不会渲染
子类(span);
变量坐标={
顶部:span.offsetTop+parseInt(计算出的['borderTopWidth']),
左:span.offsetLeft+parseInt(计算出的['borderLeftWidth'])
};
如果(调试){
span.style.backgroundColor='#aaa';
}否则{
文件.正文.删除文件(div);
}
返回坐标;
}
if(模块类型!=“未定义”&&typeof module.exports!=“未定义”){
module.exports=getCaretCoordinates;
}else if(isBrowser){
window.getCaretCoordinates=getCaretCoordinates;
}
}());
这是我的身份证号码谢谢他

限制: 它只给出元素的坐标,但我想得到整个文档的坐标

为了修复这个限制,我添加了另一个函数,该函数将查找元素相对于整个文档的坐标
<script type="text/javascript">
/* Main Function
----------------------------------------------- */
function myFunction(Desired_ID){
    // Extra Codes Here ETC...
    document.getElementById(Desired_ID.id).style.backgroundColor = "red";
    // Extra Codes Here ETC...
    var coordinates = getCaretCoordinates(Desired_ID, Desired_ID.selectionStart);
    alert(coordinates.left + ", " + coordinates.top);
    // Extra Codes Here ETC...
}

/* Get Caret XY Coordinate
----------------------------------------------- */
/* jshint browser: true */
(function () {

// The properties that we copy into a mirrored div.
// Note that some browsers, such as Firefox,
// do not concatenate properties, i.e. padding-top, bottom etc. -> padding,
// so we have to do every single property specifically.
var properties = [
  'direction',  // RTL support
  'boxSizing',
  'width',  // on Chrome and IE, exclude the scrollbar, so the mirror div wraps exactly as the textarea does
  'height',
  'overflowX',
  'overflowY',  // copy the scrollbar for IE

  'borderTopWidth',
  'borderRightWidth',
  'borderBottomWidth',
  'borderLeftWidth',
  'borderStyle',

  'paddingTop',
  'paddingRight',
  'paddingBottom',
  'paddingLeft',

  // https://developer.mozilla.org/en-US/docs/Web/CSS/font
  'fontStyle',
  'fontVariant',
  'fontWeight',
  'fontStretch',
  'fontSize',
  'fontSizeAdjust',
  'lineHeight',
  'fontFamily',

  'textAlign',
  'textTransform',
  'textIndent',
  'textDecoration',  // might not make a difference, but better be safe

  'letterSpacing',
  'wordSpacing',

  'tabSize',
  'MozTabSize'

];

var isBrowser = (typeof window !== 'undefined');
var isFirefox = (isBrowser && window.mozInnerScreenX != null);

function getCaretCoordinates(element, position, options) {
  if(!isBrowser) {
    throw new Error('textarea-caret-position#getCaretCoordinates should only be called in a browser');
  }

  var debug = options && options.debug || false;
  if (debug) {
    var el = document.querySelector('#input-textarea-caret-position-mirror-div');
    if ( el ) { el.parentNode.removeChild(el); }
  }

  // mirrored div
  var div = document.createElement('div');
  div.id = 'input-textarea-caret-position-mirror-div';
  document.body.appendChild(div);

  var style = div.style;
  var computed = window.getComputedStyle? getComputedStyle(element) : element.currentStyle;  // currentStyle for IE < 9

  // default textarea styles
  style.whiteSpace = 'pre-wrap';
  if (element.nodeName !== 'INPUT')
    style.wordWrap = 'break-word';  // only for textarea-s

  // position off-screen
  style.position = 'absolute';  // required to return coordinates properly
  if (!debug)
    style.visibility = 'hidden';  // not 'display: none' because we want rendering

  // transfer the element's properties to the div
  properties.forEach(function (prop) {
    style[prop] = computed[prop];
  });

  if (isFirefox) {
    // Firefox lies about the overflow property for textareas: https://bugzilla.mozilla.org/show_bug.cgi?id=984275
    if (element.scrollHeight > parseInt(computed.height))
      style.overflowY = 'scroll';
  } else {
    style.overflow = 'hidden';  // for Chrome to not render a scrollbar; IE keeps overflowY = 'scroll'
  }

  div.textContent = element.value.substring(0, position);
  // the second special handling for input type="text" vs textarea: spaces need to be replaced with non-breaking spaces - http://stackoverflow.com/a/13402035/1269037
  if (element.nodeName === 'INPUT')
    div.textContent = div.textContent.replace(/\s/g, '\u00a0');

  var span = document.createElement('span');
  // Wrapping must be replicated *exactly*, including when a long word gets
  // onto the next line, with whitespace at the end of the line before (#7).
  // The  *only* reliable way to do that is to copy the *entire* rest of the
  // textarea's content into the <span> created at the caret position.
  // for inputs, just '.' would be enough, but why bother?
  span.textContent = element.value.substring(position) || '.';  // || because a completely empty faux span doesn't render at all
  div.appendChild(span);

  var coordinates = {
    top: span.offsetTop + parseInt(computed['borderTopWidth']),
    left: span.offsetLeft + parseInt(computed['borderLeftWidth'])
  };

  if (debug) {
    span.style.backgroundColor = '#aaa';
  } else {
    document.body.removeChild(div);
  }

  return coordinates;
}

if (typeof module != 'undefined' && typeof module.exports != 'undefined') {
  module.exports = getCaretCoordinates;
} else if(isBrowser){
  window.getCaretCoordinates = getCaretCoordinates;
}

}());
</script>
<script type="text/javascript">
/* Get Element XY Coordinate
----------------------------------------------- */
function getElementCoords(elem) { // crossbrowser version
    var box = elem.getBoundingClientRect();

    var body = document.body;
    var docEl = document.documentElement;

    var scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop;
    var scrollLeft = window.pageXOffset || docEl.scrollLeft || body.scrollLeft;

    var clientTop = docEl.clientTop || body.clientTop || 0;
    var clientLeft = docEl.clientLeft || body.clientLeft || 0;

    var top  = box.top +  scrollTop - clientTop;
    var left = box.left + scrollLeft - clientLeft;

    return { top: Math.round(top), left: Math.round(left) };
}
</script>
<script type="text/javascript">
/* Main Function
----------------------------------------------- */
function myFunction(Desired_ID){
    // Extra Codes Here ETC...
    document.getElementById(Desired_ID.id).style.backgroundColor = "red";
    // Extra Codes Here ETC...
    var coordinates = getCaretCoordinates(Desired_ID, Desired_ID.selectionStart);
    var elementCoordinates = getElementCoords(Desired_ID);
    var topPosition = coordinates.top + elementCoordinates.top;
    var leftPosition = coordinates.left + elementCoordinates.left;
    alert(leftPosition + ", " + topPosition);
    // Extra Codes Here ETC...
}
</script>