截断文本并在鼠标悬停时显示

Truncate the text and show it on mouseover

本文关键字:悬停 显示 鼠标 文本      更新时间:2023-09-26

我需要截断文本(用…在最后)和鼠标悬停时,整个文本应该展开。

我尝试用下面的代码截断。这段代码的问题是,它在点击...时扩展了内容但我需要它在用户鼠标移到p标签

上的任何地方时打开
var len = 100;
var p = document.getElementById('truncateMe');
if (p) {
  var trunc = p.innerHTML;
  if (trunc.length > len) {
    trunc = trunc.substring(0, len);
    trunc = trunc.replace(/'w+$/, '');
    trunc += '<a href="#" ' +
      'onmouseover="this.parentNode.innerHTML=' +
      'unescape('''+escape(p.innerHTML)+''');return false;">' +
      '...<'/a>';
    p.innerHTML = trunc;
  }
}

我正在寻找一种简单的方法来做这件事。

提前感谢。

PS:没有CSS解决方案,因为它不兼容所有浏览器(IE7)

你可以这样使用Jquery:

HTML:

<p>Some Text</p>

JS:

var lengthText = 30;
var text = $('p').text();
var shortText = $.trim(text).substring(0, lengthText).split(" ").slice(0, -1).join(" ") + "...";
$('p').text(shortText);
$('p').hover(function(){
    $(this).text(text);
}, function(){
    $(this).text(shortText);
});

演示:http://jsfiddle.net/1yzzbv4b/2/

或者你也可以通过css3属性text-overflow:ellipsis;

来实现CSS:
p{
    text-overflow:ellipsis;
    width: 250px;
    white-space: nowrap;
    overflow: hidden;
}
p:hover{
    text-overflow:clip;
    width:auto;
    white-space: normal;
}

演示:http://jsfiddle.net/1yzzbv4b/

假设您将p -elements的类设置为escape-text,那么下面的jquery代码应该可以工作。

$(document).ready(function() {
    $ps = $('.escape-text');

    $ps.each(function(i, el) {
        $(el).data('full-text', el.innerHTML);
        strip(el);
    });
    $ps.on('mouseover', function() {
        $(this).text($(this).data('full-text'));
    }).on('mouseout', function() {
        $(this).text(strip(this));
    })
});
var length = 100;
var strip = function(el) {
    el.innerHTML = el.innerHTML.substr(0, length) + '...';
}