vue-line-clamp.esm.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. const currentValueProp = "vLineClampValue";
  2. function defaultFallbackFunc(el, bindings, lines) {
  3. if (lines) {
  4. let lineHeight = parseInt(bindings.arg);
  5. if (isNaN(lineHeight)) {
  6. console.warn(
  7. "line-height argument for vue-line-clamp must be a number (of pixels), falling back to 16px"
  8. );
  9. lineHeight = 16;
  10. }
  11. let maxHeight = lineHeight * lines;
  12. el.style.maxHeight = maxHeight ? maxHeight + "px" : "";
  13. el.style.overflowX = "hidden";
  14. el.style.lineHeight = lineHeight + "px"; // to ensure consistency
  15. } else {
  16. el.style.maxHeight = el.style.overflowX = "";
  17. }
  18. }
  19. const truncateText = function(el, bindings, useFallbackFunc) {
  20. let lines = parseInt(bindings.value);
  21. if (isNaN(lines)) {
  22. console.error("Parameter for vue-line-clamp must be a number");
  23. return;
  24. } else if (lines !== el[currentValueProp]) {
  25. el[currentValueProp] = lines;
  26. if (useFallbackFunc) {
  27. useFallbackFunc(el, bindings, lines);
  28. } else {
  29. el.style.webkitLineClamp = lines ? lines : "";
  30. }
  31. }
  32. };
  33. const VueLineClamp = {
  34. install(Vue, options) {
  35. options = Object.assign(
  36. { importCss: false, textOverflow: "ellipsis" },
  37. options
  38. );
  39. const styles =
  40. "display:block;display:-webkit-box;-webkit-box-orient:vertical;overflow:hidden;text-overflow:" +
  41. options.textOverflow;
  42. if (options.importCss) {
  43. const stylesheets = window.document.styleSheets,
  44. rule = `.vue-line-clamp{${styles}}`;
  45. if (stylesheets && stylesheets[0] && stylesheets.insertRule) {
  46. stylesheets.insertRule(rule);
  47. } else {
  48. let link = window.document.createElement("style");
  49. link.id = "vue-line-clamp";
  50. link.appendChild(window.document.createTextNode(rule));
  51. window.document.head.appendChild(link);
  52. }
  53. }
  54. const useFallbackFunc =
  55. "webkitLineClamp" in document.body.style
  56. ? undefined
  57. : options.fallbackFunc || defaultFallbackFunc;
  58. Vue.directive("line-clamp", {
  59. currentValue: 0,
  60. bind(el) {
  61. if (!options.importCss) {
  62. el.style.cssText += styles;
  63. } else {
  64. el.classList.add("vue-line-clamp");
  65. }
  66. },
  67. inserted: (el, bindings) => truncateText(el, bindings, useFallbackFunc),
  68. updated: (el, bindings) => truncateText(el, bindings, useFallbackFunc),
  69. componentUpdated: (el, bindings) =>
  70. truncateText(el, bindings, useFallbackFunc)
  71. });
  72. }
  73. };
  74. export default VueLineClamp;