我需要截断文本(最后是......),鼠标悬停时应该扩展整个文本。
我试图通过以下代码截断。这个代码的问题是,它会在点击...
时扩展内容,但是当用户将鼠标悬停在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)不兼容。
答案 0 :(得分:4)
你可以使用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);
});
DEMO: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;
}
答案 1 :(得分:0)
假设您将p
- 元素的类设置为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) + '...';
}