我试图在鼠标上突出显示文档正文中的各个跨度。我的问题是,出于某种原因,默认情况下每个元素都是突出显示的,我似乎无法让它在 window.getSelection() 上工作。我只需要在单击它时突出显示跨度。
有人知道一个快速的方法吗?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>The HTML5 Herald</title>
<meta name="description" content="The HTML5 Herald">
<meta name="author" content="SitePoint">
<link rel="stylesheet" href="./styles.css">
</head>
<body>
<h2>doc body</h2>
<div id="docbod" class="docbody"> </div>
<script src="./highlight.js"></script>
</body>
</html>
var documentbody = document.getElementById("docbod");
/* turns every word in the document into an element then appends them to the div that contains the doc body */
function splitdocintowords(div) {
var divarray = []
var state = ["hey", "there", "how", "are", "you", "doing?"]
for (let i = 0; i < state.length; i++) {
span = document.createElement("span")
span.textContent = state[i]
//-------^
span.id = "word" + i;
span.classList.add("textBackground")
span.addEventListener("onMouseup", highlight(span));
div.append(span);
div.append(" ");
}
}
splitdocintowords(documentbody);
/* highlights a selected word within the document*/
function highlight (element){
element.style.background='yellow';
console.log("selected element")
}
最佳答案
你在添加事件监听器时出错,事件的名称是'mouseup'。
span.addEventListener("mouseup", () => span.style.background = 'yellow');
关于javascript - 在 onmouseup 上突出显示 div 内的 span 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58322920/