我有一个div,其中包含一些文本,最初没有包装,并显示省略号,但我希望让用户能够单击read选项,然后展开div以显示整个文本。
但是,我希望能够检测到文本是否足够小以适应div,而不需要从一行展开它,如果是这样,则隐藏更多的显示选项。
下面链接到我一直在修改的JS Fiddle:
http://jsfiddle.net/M2APS/44/
其中的密码是:
$(document).bind('pageshow', function() {
$(".text-size").click(function() {
$(".ui-li > div").toggleClass("less");
if ($(".text-size").html() == "Read more...") {
$(".text-size").html("Read less...");
} else {
$(".text-size").html("Read more...");
}
});
});.less {
word-wrap: break-word;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
.more {
white-space: normal;
}
.text-size {
display: block;
text-align: right;
padding-top: 10px;
color: blue !important;
cursor: pointer;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-role="page" id="p1">
<div data-role="content">
<ul data-role="listview" data-inset="true">
<li data-role="list-divider">Item Title</li>
<li>
<div class="less">
Need to detect if this text is long enough to show the "Read More" if it is not don't
</div>
<div class="text-size">Read more...</div>
</li>
</ul>
</div>
</div>
是否可以检测到文本是否足够短,以适应div,然后隐藏读更多选项?
发布于 2014-05-19 17:31:35
您可以将DIV width与scrollWidth进行比较,以检测文本是否溢出:
if ($('.less')[0].scrollWidth <= $('.less').width()) {
$(".text-size").hide();
}演示: http://jsfiddle.net/ygalanter/M2APS/50/
发布于 2014-05-19 17:32:34
有一个适合您需要的jQuery插件:http://jedfoster.com/Readmore.js/
发布于 2014-05-19 17:32:55
这可能是不完整的,但是您可能希望根据jQuery提供的jQuery()方法(http://api.jquery.com/height/)来做一些事情。
$(document).bind('pageshow', function() {
if($(".ui-li > div").height() > 20) {
$(".ui-li > div").addClass("less");
$(".text-size").click(function(){
$(".ui-li > div").toggleClass("less");
if($(".text-size").html() == "Read more...")
{
$(".text-size").html("Read less...");
}
else
{
$(".text-size").html("Read more...");
}
});
} else {
// one liner
$(".text-size").hide();
}});
用小提琴检查我的解决方案。
http://jsfiddle.net/gZe8b/
https://stackoverflow.com/questions/23743669
复制相似问题