如何使元素靠近光标
How can I get the element near the cursor?
就像我在title中说的那样。我想要定位光标附近的元素
<style type="text/css">
span{
display: inline-block;
min-width: 80px;
border-bottom: 2px solid black;
}
</style>
<div contenteditable="true">
<span></span>
<span></span>
<span></span>
</div>
当用户输入一些单词时,我很想知道哪个单词在里面
你可以这样做:
// Get all span-elements
var elements = document.getElementsByClassName("span_element");
// Cycle through them and add an onmouseover-function to them
for(var i = 0, length = elements.length; i < length; i++) {
elements[i].onmouseover = function() {
console.log(this.id);
}
}
因此,您的html
应该看起来像这样,例如(处理元素):
<div contenteditable="true">
<span id="span1" class="span_element"></span>
<span id="span2" class="span_element"></span>
<span id="span3" class="span_element"></span>
</div>
旁注:使用jQuery,这要容易得多,因为您有。focus()。
旁注2:请记住,mousecursor(如您最初的帖子和我的回答所述)和插入位置(用户实际键入的地方)之间存在差异。
你可以给onmouseover事件附加一个监听器,当鼠标在你的span上时触发一个函数。
<div contenteditable="true">
<span onmouseover="myFunction1()"></span>
<span onmouseover="myFunction2()"></span>
<span onmouseover="myFunction3()"></span>
</div>
function myFunction1() {
// the mouse is above span 1
}
// etc...
官方文档在这里
Edit:在理解OP正在寻找的内容后修改答案
当您使用jQuery并处理动态添加的元素时,我建议您使用如下内容:
$(document).on('mouseenter', 'div span', function() {
$(this).css('border-color', 'red');
})
.on('mouseleave', 'div span', function() {
$(this).css('border-color', 'black');
});
我在这里创建了一个JSFiddle示例
我已经找到了一种使用浏览器API document.elementFromPoint(x,y)
查找光标附近DOM元素的通用方法。我在本文中使用了这种方法,并在npm上发布了一个名为cursor-nearby-elements
相关文章:
- 自定义函数中的光标位置
- 在Widget代码中使用javascript从左向右滑动光标图像
- 将文本插入光标所在的文本区域
- 鼠标光标-用于wordpress网站
- 在Widget代码中没有jQuery的情况下,用光标图像从左滑动到右
- 我可以让我的Ajax调用引起一个“;进行中”;光标
- 默认光标在IE和Mozilla中不起作用
- onmousedown更改光标;可能需要控制事件冒泡
- 由于滑块的原因,光标始终是D3中的十字光标
- 即使光标位于屏幕边缘,也可以跟踪鼠标速度
- draggableCursor没有't更改为等待光标
- 使用地理坐标,对更靠近用户的对象进行排序'的位置
- 在窗口中单击按钮完成之前,光标不会停止.请继续卸载
- JQuery BlockUI鼠标加载光标没有't在Google Chrome中返回默认值
- 图像阵列预加载时显示沙漏光标
- 如何检查光标是否位于指定的标记之间
- HTML5-画布元素&自定义光标
- ReacJS与猴面包树,如何在卸载组件后释放光标
- forEach在光标上
- 如何使元素靠近光标