2011-05-18 47 views
2

在我的Ruby On Rails应用程序中,我有这样的情况:当我显示字符串值时,它应该只显示100个字符,当用户将鼠标悬停在字符串值上时,它应显示所有字符串值。截断并展开Ruby On Rails中的字符串

例如:一个例子是人..

在鼠标:一个例子是永远比描述的情况更好。

我尝试使用Ruby On Rails构建func => truncate(title.to_s,:length => 100)。我知道我只能通过使用上述截断。

什么是上述两种Ruby on Rails的溶液或jQquery解决方案的解决方案是最好的

回答

2

如果你想扩展在鼠标悬停文字,那么我建议实施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();

0

这可以很好地工作。

$(".inner").mouseover(function(){ 
    $(".inner").animate({"marginLeft": "-=100px"}, "slow"); 
}); 

$(".inner").mouseout(function(){ 
    $(".inner").animate({"marginLeft": "+=100px"}, "slow"); 
}); 

看到它在这里工作:http://jsfiddle.net/R4Xyd/5/