微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript-可折叠div,但是从某个变量中定义的某个点开始

例如.我有一个div,其中包含所有文本,例如:

<div class="text-container">
<p>
Though we welcome the idea of a smaller connector, we're miffed that Apple Couldn't just adopt the semi-industry standard of Micro-USB. That would make things easier for smartphone users across the globe. Yet, even so, the smaller connector may be a smart move for the future. The 30-pin connector has been around since 2003, long before the iPhone even existed: frankly, it's a dust magnet. A smaller connector helps shave extra space to achieve a smaller phone with perhaps a bigger battery. The new connector cable will mainly be used for syncing and charging by most people who own an Apple TV or Bluetooth/AirPlay accessories.
</p>
</div>

我想创建这样的东西:

<div class="text-container">
<p>
Though we welcome the idea of a smaller connector...<a href="some-javascript-to-show-more">[show more]</a>
</p>
</div>

我想我应该获取div的所有内容,然后找到第一个例如50个字符,并在其中放置一个链接,所有其他文本放在div中将被隐藏,单击链接后,将显示其他内容.

它应该像切换一样,如果展开则将文本从[显示更多]更改为[显示较少],反之亦然.

有什么建议如何使用普通的javascript和jquery本身而不使用其他jQuery插件来实现此目标?

解决方法:

这是另一种解决方案.

它不仅可以将中间的单词切掉,还可以检查结尾,标点和长单词.

$(".text-container p").each(function() {
    var val = $.trim(this.innerHTML),
        parsed = val.split(/\s+/),
        cut = parsed;

    // for each word
    for (var i = 0, k = 0; i < parsed.length; i++) {
        k += parsed[i].length + 1;

        if (k - 1 > 50) {
            cut = parsed.slice(0, i);
            break;
        }
    }

    // if one long word
    if (cut.length == 0) {
        cut.push(parsed[0].substring(0, 50));
    }

    val = cut.join(" ");

    // if the text is long enough to cut
    if (cut.length != parsed.length) {
        this.innerHTML = val.replace(/[.,;?!]$/, "")
            + "<span>...</span> ";

        $("<span />")
            .css("display", "none")
            .html(parsed.slice(cut.length).join(" ") + " ")
            .appendTo(this);

        $("<a />", {
            href : "#",
            text : "[show more]"
        }).on("click", function(e) {
            var sh = this.innerHTML == "[show more]";
            $(this).prev("span").toggle(sh).prev("span").toggle(!sh);
            this.innerHTML = sh ? "[show less]" : "[show more]";
            e.preventDefault();
        }).appendTo(this);
    } else {
        this.innerHTML = val;
    }
});

演示:http://jsfiddle.net/xRuch/

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐