HTML5触摸事件:触及单词

时间:2017-11-14 09:40:27

标签: javascript html5

我正在为移动用户构建我的网站的dicionary功能。 我想要这个功能: 用户触摸一个单词,弹出窗口显示其定义。

我发现了HTML5的触控API。 但无法弄清楚如何触及这个词。 任何提示?

2 个答案:

答案 0 :(得分:2)

由于Range API及其方便的getBoundingClientRect方法,您可以实现这一目标 实际上,这种方法允许我们获取textNode的位置,而通常我们只能得到一个Element的位置。

我们所要做的就是首先检索被点击的原始textNode,将其内容拆分为与单词一样多的textNodes,并抓住我们想要的那个。

document.onclick = function(e){ console.log(getWord(e));};
// didn't really test with touch device yet, but should be about the same...
document.ontouchstart = function(e){ console.log(getWord(e.touches[0]));};

function getWord(e) {
  // FF gives us a shortcut
  var target = e.explicitOriginalTarget || e.target,
    // We will use this to get the positions of our textNodes
    range = document.createRange(),
    rect, i;
  // so first let's get the textNode that was clicked
  if (target.nodeType !== 3) {
    var children = target.childNodes;
    i = 0;
    while (i < children.length) {
      range.selectNode(children[i]);
      rect = range.getBoundingClientRect();
      if (rect.left <= e.clientX && rect.right >= e.clientX &&
        rect.top <= e.clientY && rect.bottom >= e.clientY) {
        target = children[i];
        break;
      }
      i++;
    }
  }
  if (target.nodeType !== 3) {
    return '[not a textNode]';
  }
  // Now, let's split its content to words
  var words = target.nodeValue.split(' '),
    textNode, newText;
  i = 0;
  while (i < words.length) {
    // create a new textNode with only this word
    textNode = document.createTextNode((i ? ' ' : '') + words[i]);
    newText = words.slice(i + 1);
    // update the original node's text
    target.nodeValue = newText.length ? (' ' + newText.join(' ')) : '';
    // insert our new textNode
    target.parentNode.insertBefore(textNode, target);
    // get its position
    range.selectNode(textNode);
    rect = range.getBoundingClientRect();
    // if it is the one
    if (rect.left <= e.clientX && rect.right >= e.clientX &&
      rect.top <= e.clientY && rect.bottom >= e.clientY) {
      return words[i];
    }
    i++;
  }
};
<p>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ac fermentum ipsum, in efficitur felis. Nam fringilla semper lectus, pretium luctus tortor. Pellentesque vel aliquet orci. Quisque at accumsan felis. Phasellus a ligula congue, viverra tellus
  sit amet, consequat arcu. Mauris et congue diam, eget vehicula ante. Curabitur varius augue eget augue posuere, ut tincidunt purus sodales. Suspendisse luctus fermentum justo, sed scelerisque ipsum dignissim nec.
</p>
<p>
  Suspendisse sed dui elit. Vivamus laoreet ipsum ut metus finibus, eu ultrices lorem bibendum. Fusce ante nibh, egestas nec neque id, semper volutpat orci. Donec a porta nunc. Sed interdum hendrerit mauris. Donec sed semper eros. Integer rhoncus diam quis
  augue ornare consequat. Sed eleifend congue ante quis malesuada. Maecenas et purus venenatis arcu malesuada condimentum id quis nunc. Integer non suscipit sapien, id iaculis mi.
</p>
<p>
  Mauris cursus mauris vitae nulla tempor lacinia. Quisque tristique ullamcorper magna et consequat. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Phasellus faucibus sit amet enim non sollicitudin. Aliquam malesuada,
  massa hendrerit condimentum pulvinar, ex est finibus massa, at efficitur velit est eu dolor. Pellentesque facilisis ligula hendrerit lacus efficitur venenatis. Ut pretium turpis quis laoreet mattis. Quisque tempor ornare maximus. Nunc augue urna, egestas
  non lectus at, fringilla pharetra nisl. Pellentesque ac quam cursus, volutpat libero eget, ultricies dolor. Donec eleifend iaculis dui dignissim pulvinar. Cras semper vehicula augue, ut ultricies arcu consectetur ut. Mauris congue turpis justo, ac feugiat
  dolor semper nec. Donec id augue posuere, efficitur nunc in, hendrerit est. Morbi eget pretium odio.
</p>
<p>
  Morbi at volutpat nulla. Pellentesque elementum blandit imperdiet. Morbi id lacinia quam. Sed sed accumsan mauris. Donec nulla mi, rutrum id blandit id, hendrerit at turpis. Integer ante orci, venenatis a felis id, suscipit dignissim metus. Pellentesque
  dictum, lectus aliquam facilisis mattis, nisi est porttitor nulla, et semper enim ante quis ex. Quisque ante magna, viverra et ante quis, fringilla tempor mauris. Phasellus posuere nulla in eleifend egestas. Proin augue arcu, semper quis metus sit amet,
  placerat porta lorem. Integer tempus mi at faucibus posuere. Vestibulum ut malesuada turpis. In malesuada eros nisl, eget laoreet velit auctor vitae.
</p>
<p>
  Aliquam maximus varius metus vel congue. Ut tristique risus metus, in tempor leo tempor laoreet. Donec scelerisque ipsum vitae nisi facilisis eleifend. Vivamus condimentum risus non lectus bibendum elementum. Cras vitae malesuada lorem. Curabitur et posuere
  massa, ut luctus mi. Sed et enim nec nisl sollicitudin semper. Donec eget consectetur leo, a faucibus nulla. Nam accumsan hendrerit neque, ultrices aliquam ex auctor id. Nunc euismod faucibus ullamcorper. Sed ornare interdum congue. Quisque eget erat
  erat. Morbi congue orci vitae porttitor semper.
</p>

答案 1 :(得分:1)

这将是一个有点棘手的问题。如果您想知道句子中触及的特定单词,您应该在单独的范围内保存单词,在所有跨度上注册触摸事件并在触摸时获取文本内容。 有关事件监听器和

,请参阅https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

https://developer.mozilla.org/en-US/docs/Web/API/Touch_events/Using_Touch_Events用于捕捉触摸事件。