【问题标题】:JavaScript - Select span text on mouse hoverJavaScript - 在鼠标悬停时选择跨度文本
【发布时间】:2015-03-03 12:46:33
【问题描述】:

我有这个 HTML 代码。

<div class="dontsplit" onmouseover="selCode('c111');">
  Face savoring delicious food <span class="notranslate" id="c111">????</span>
</div>

当鼠标悬停在 div 上时,我想选择 span 标签之间的值。我使用的代码是这样的。

function selCode(objId) {
    if(document.selection) {
        var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById(objId));
        range.select();
    } else if(window.getSelection) {
        var range = document.createRange();
        range.selectNode(document.getElementById(objId));
        window.getSelection().addRange(range);
    }
}

但它似乎不起作用。我如何获得这项工作?

我重复一遍。当鼠标悬停在 div 上时,我需要自动选择 span 之间的文本。所以很容易被复制。提前致谢!

【问题讨论】:

  • $(".notranslate").text()?
  • 他使用 vanilla ...这里不需要 jQuery
  • 欢迎使用 jQuery 方法。
  • 好的...那么最好从问题中删除jQuery标签...感到困惑。
  • 不不...任何我需要的方法。

标签: javascript jquery html


【解决方案1】:

您的脚本适用于第一个鼠标悬停,但第二个向内提供错误Discontiguous selection is not supported.,因此在进行新选择之前清除现有选择。

function selCode(objId) {
    if (document.selection) {
        var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById(objId));
        range.select();
    } else if (window.getSelection) {
        var range = document.createRange();
        range.selectNode(document.getElementById(objId));
        window.getSelection().removeAllRanges();
        window.getSelection().addRange(range);
    }
}

演示:Fiddle

【讨论】:

【解决方案2】:

我认为这应该会有所帮助。

你可以使用 jQuery .text() 方法。

你有一个 spannotranslate 类。

所以你可以这样做来获取文本:

$(".notranslate").text();

http://jsfiddle.net/L8r6ns88/

【讨论】:

  • 谢谢!它正在“警告”文本。无论如何选择文本或将其复制到剪贴板?
  • 只是一个演示..您可以根据自己的要求进行修改。
  • 好的。非常感谢!
【解决方案3】:

试试这个。我正在使用 jquery 来完成这项任务。

HTML

<div class="dontsplit">
  Face savoring delicious food <span class="notranslate" id="c111">?</span>
</div>

JS

$(function(){

  $('.dontsplit').on('mouseover','.notranslate', function(){
  console.log($(this).text()); //see result
 })
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    • 2017-10-14
    • 2014-12-05
    • 1970-01-01
    • 1970-01-01
    • 2014-10-03
    • 2019-03-07
    相关资源
    最近更新 更多