我希望在一定数量的字符后隐藏div中的文本,并将其限制在单词上。我找到了这个解决方案:jquery limit text by length但它没有办法关闭div备份或中断单词。
这是我迄今为止所拥有的...这允许我打开和关闭div。但是我希望它有所不同,因为我希望它能够检查文本,直到达到一定数量的字符。然后它会将DIV从该位置包装到文本的末尾,然后可以使用hide()方法隐藏它。我必须将它添加到数千个节点。所以我无法浏览每一个并添加本例中的显示/隐藏范围
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
function showStuff(id) {
document.getElementById(id).style.display = 'block';
}
function hideStuff(id) {
document.getElementById(id).style.display = 'none';
}
</script>
<style type="text/css">
span.read-more { cursor: pointer; color: red; }
span.more { display: none; }
</style>
</head>
<body>
<p><a href="#" onclick="showStuff('answer1'); return false;">What price are your apples?</a><br>
<span id="answer1" style="display: none;">Our apples are 30 pence each. If you buy 10 or more we can sell them at a discounted bulk rate of 25 pence each.
<a href="#" onclick="hideStuff('answer1'); return false;">Close</a><br>
</span></p>
</body>
</html>
我发现这是对另一个问题的回答,但我不知道如何合并这两组功能:
<script type="text/javascript" charset="utf-8">
$(function(){
var $elem = $('p'); // The element or elements with the text to hide
var $limit = 10; // The number of characters to show
var $str = $elem.html(); // Getting the text
var $strtemp = $str.substr(0,$limit); // Get the visible part of the string
$str = $strtemp + '<span class="hide">' + $str.substr($limit,$str.length) + '</span>'; // Recompose the string with the span tag wrapped around the hidden part of it
$elem.html($str); // Write the string to the DOM
})
</script>
答案 0 :(得分:2)
您可以轻松地执行以下操作:
if ($(".yourelement").html().length > 50) { // if count is greater than 50
$(".yourelement").slideUp("slow");
}