js中如何获取光标所在的元素

<div contenteditable="true">
    zinc <font size="3">haha</font><br/>
    啦啦啦</div>

js中如何获取光标所在的元素,而不是鼠标点击时所点击的区域的元素。

上面的代码,点击界面中第一行后面的空白区域,光标会落在font标签里,但是鼠标获取的元素是div,如何做到,点击后是获取光标落在的标签。


慕仙森
浏览 1841回答 1
1回答

慕沐林林

用event.target不可以么?补充:我自己做了测试:<!DOCTYPE html><html><head>&nbsp; &nbsp; <meta charset="UTF-8">&nbsp; &nbsp; <title>Document</title>&nbsp; &nbsp; <style>&nbsp; &nbsp; div {&nbsp; &nbsp; &nbsp; &nbsp; border:1px solid red;&nbsp; &nbsp; &nbsp; &nbsp; width:400px;&nbsp; &nbsp; &nbsp; &nbsp; height:400px;&nbsp; &nbsp; &nbsp; &nbsp; }</style></head><body>&nbsp; &nbsp; <div contenteditable="true">&nbsp; &nbsp; zinc <font size="3" data="font">haha</font><br/>&nbsp; &nbsp; 啦啦啦</div></body><script>&nbsp; &nbsp; window.onload = function() {&nbsp; &nbsp; &nbsp; &nbsp; document.onclick = function (e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(e.target);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(e.target.getAttribute("data") == 'font') {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.target.style.color = 'blue';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }</script></html>这个可以直接跑,当你鼠标点击font的时候,font变蓝了
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript