gpt4 book ai didi

javascript - chop 文本并在鼠标悬停时显示

转载 作者:行者123 更新时间:2023-11-29 18:13:36 25 4
gpt4 key购买 nike

我需要 chop 文本(末尾有 ...),并且在鼠标悬停时整个文本应该得到扩展。

我尝试通过以下代码进行 chop 。这段代码的问题是,它在点击 ... 时扩展了内容,但我需要在用户将鼠标悬停在 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;
}
}

DEMO

我正在寻找一种简单的方法。

提前致谢。

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/

关于javascript - chop 文本并在鼠标悬停时显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25261234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com