检测光标是否在链接内并获取其href属性



在一个可满足的div需要检测光标是否在<a></a>范围内
如果在控制台我需要href属性
在下面的例子中-如果光标在google控制台应该是https://google.com/
任何帮助,使用jquery或纯js

document.onselectionchange = () => {
var selection = window.getSelection();
var parent = selection.parentNode;
console.log(parent);  // why undefined
// if(parent is a link){console.log(parent.attr('href'));}
};
.ed{width:50%; margin:0 auto; height:100vh; padding:9px; background:orange;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='ed' id='ed' contenteditable>
<div>lorem</div>
<div><a href='https://google.com/'>google</a></div>
</div>

parent为JS保留字。https://www.w3schools.com/js/js_reserved.asp

document.querySelectorAll('#ed a').forEach(link => {
link.addEventListener("mouseover", function(event) {
console.log(event.target.href)
});
})
.ed {
width: 50%;
margin: 0 auto;
height: 100vh;
padding: 9px;
background: orange;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='ed' id='ed' contenteditable>
<div>lorem</div>
<div><a href='https://google.com/'>google</a></div>
<div><a href='https://test.com/'>test.com</a></div>
</div>

如果您想仅在上检查href属性,则聚焦光标在文本上,而不是将鼠标移到上您可以在选择时使用focusNode实例类型

.ed{width:50%; margin:0 auto; height:100vh; padding:9px; background:orange;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='ed' id='ed' contenteditable>
<div>lorem</div>
<div><a href='https://google.com/'>google</a></div>
</div>
document.onselectionchange = () => {
var selection = window.getSelection();
var parentElement = selection.focusNode.parentElement;
if(parentElement instanceof HTMLAnchorElement){
console.log(parent.href);
}
};

最新更新