首页 > 解决方案 > 检查选定的文本是否被点击

问题描述

我有一个 div 元素,里面有文本。我想知道用户点击了什么,选择了文本还是没有选择?区分选中文本点击和未选中文本点击的主要目标

标签: javascripthtmljquerycss

解决方案


这将运行 2 个不同的功能。当你点击选中的文本时,它会运行一个函数,使背景变红,当你点击未选中的文本时,它会运行另一个函数,使背景变绿。希望这有帮助。

function red(){

//this function will be executed when the selected text is clicked

document.body.style.backgroundColor = "red";
}
function green(){

/*this function will be executed when the non-selected text is clicked*/

document.body.style.backgroundColor = "green";
}
body{
font-size:30px;
}
<body>
<div><span onclick="red()" style="background-color:yellow">this text is selected</span>,<span onclick="green()"> this text is not</span></div>
</body>


推荐阅读