javascript - 在 onmouseup 上突出显示 div 内的 span 标签

标签 javascript html

我试图在鼠标上突出显示文档正文中的各个跨度。我的问题是,出于某种原因,默认情况下每个元素都是突出显示的,我似乎无法让它在 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/

相关文章:

html - 设置多个备用表格行的样式

javascript - 要求 js 缓存设置 urlArgs 半身像的设置文件

asp.net - CSS div 位置问题

python - Google App Engine 在按钮点击时重定向到用户登录

javascript - 在javascript函数中更改文档背景图像

jquery - 如何使用 jquery tocify 或 bootstrap toc 修复内容 div 高度

javascript - 更改 Canvas 线,或两点之间的调整线

javascript - 从 Spotify API 检索匹配的歌曲 URI

javascript - 一切正常,但是当我单击编辑按钮时,每次都会添加一个逗号 (,)。我不会发现哪里出了问题?

javascript - 查看具有为所有 div 调用函数的同一类的多个 div?