banner image

Cắt ngắn đoạn văn bản với dotdotdotJS


Xin chào các bạn! Trong lúc các bạn làm việc với CSS có rất nhiều yêu cầu là cắt chuỗi văn bản và thêm dấu... vào sau mà ko biết nên làm thế nào. Ở bài này mình sẽ hướng dẫn các bạn sử dụng thư viện dotdotdot đơn giản để cắt chuỗi văn bản. Ok, bắt đầu thôi.

Nội dung chính

  • 1. Demo
  • 2. Link thư viện
  • 3. Sử dụng
  • 4. Lưu ý

1. Demo

Link thư viện:

http://dotdotdot.frebsite.nl/
Link demo REPL:

https://repl.it/@kentrung/Cat-ngan-doan-van-ban-voi-dotdotdotJS

2. Link thư viện

Sử dụng link CDN:

https://cdnjs.com/libraries/jQuery.dotdotdot
Sử dụng NPM:

npm i dotdotdot-js
Sử dụng github:

https://github.com/FrDH/dotdotdot-js

3. Sử dụng

Thêm thư viện vào trang web.

<script src="dotdotdot.js" />
Tạo một instance với đoạn bạn muốn cắt ngắn.

document.addEventListener( "DOMContentLoaded", () => {
   let wrapper = document.querySelector( "#element-to-truncate" );
   let options = {
      // Options go here
      callback: function( isTruncated ) {},
      /* Function invoked after truncating the text.
         Inside this function, "this" refers to the wrapper. */

      ellipsis: "\u2026 ",
      /* The text to add as ellipsis. */

      height: null,
      /* The (max-)height for the wrapper:
         null: measure the CSS (max-)height ones;
         a number: sets a specific height in pixels;
         "watch": re-measures the CSS (max-)height in the "watch". */

      keep: null,
      /* Query selector for elements to keep after the ellipsis. */

      tolerance: 0,
      /* Deviation for the measured wrapper height. */

      truncate: "word",
      /* How to truncate the text: "node", "word" or "letter". */

      watch: "window",
      /* Whether to update the ellipsis: 
         true: Monitors the wrapper width and height;
         "window": Monitors the window width and height. */
   };
   new Dotdotdot( wrapper, options );
});
Các bạn có thể xem ví dụ mình áp dụng một số option của họ tại https://repl.it/@kentrung/Cat-ngan-doan-van-ban-voi-dotdotdotJS

4. Lưu ý

+ Thư viện này chạy không cần jQuery.
+ Thư viện này nhắm vào các trình duyệt hiện đại hỗ trợ ES5, nghĩa là Internet Explorer 10 trở về trước không được hỗ trợ. Đối với IE 11, bạn sẽ cần một số polyfill. Nếu bạn cần hỗ trợ cho Internet Explorer 9 hoặc 10, hãy sử dụng phiên bản kế thừa (jQuery): phiên bản 3.2.3
Cắt ngắn đoạn văn bản với dotdotdotJS Cắt ngắn đoạn văn bản với dotdotdotJS Reviewed by kentrung on November 06, 2019 Rating: 5

No comments:

Powered by Blogger.