如果你想扩展在鼠标悬停文字,那么我建议实施jQuery的解决方案,因为它意味着那些没有JS的人可以看到全文(例如,它对于可访问性来说很好)。以下内容是基于我们在我们网站上使用的内容,并通过单击文本而不是悬停在文本上来切换完整/缩短文本,但更改为悬停事件应该非常简单。
首先将您想要自动展开/收缩的文本封装在div/span中,然后使用您可以在jQuery中稍后使用它来拾取的类。
<div class="autoShorten">An example is always better than description situation.</div>
然后创建下面的jQuery函数:
jQuery.fn.autoShorten = function() {
return this.each(function(){
if ($(this).text().length > 100) {
var words = $(this).text().substring(0,100).split(" ");
var shortText = words.slice(0, words.length - 1).join(" ") + "...";
$(this).data('replacementText', $(this).text())
.text(shortText)
.css({ cursor: 'pointer' })
.hover(function() { $(this).css({ textDecoration: 'underline' }); }, function() { $(this).css({ textDecoration: 'none' }); })
.click(function() { var tempText = $(this).text(); $(this).text($(this).data('replacementText')); $(this).data('replacementText', tempText); });
}
});
};
此功能还具有插入就一个字破省略号在单词中间
终于在,而不是利益的$(document).ready
function add $('.autoShorten').autoShorten();