code.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /**
  2. @Name:layui.code 代码修饰器
  3. @Author:贤心
  4. @License:MIT
  5. */
  6. layui.define('jquery', function(exports){
  7. "use strict";
  8. var $ = layui.$;
  9. var about = 'http://www.layui.com/doc/modules/code.html'; //关于信息
  10. exports('code', function(options){
  11. var elems = [];
  12. options = options || {};
  13. options.elem = $(options.elem||'.layui-code');
  14. options.about = 'about' in options ? options.about : true;
  15. options.elem.each(function(){
  16. elems.push(this);
  17. });
  18. layui.each(elems.reverse(), function(index, item){
  19. var othis = $(item), html = othis.html();
  20. //转义HTML标签
  21. if(othis.attr('lay-encode') || options.encode){
  22. html = html.replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&')
  23. .replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&#39;').replace(/"/g, '&quot;')
  24. }
  25. othis.html('<ol class="layui-code-ol"><li>' + html.replace(/[\r\t\n]+/g, '</li><li>') + '</li></ol>')
  26. if(!othis.find('>.layui-code-h3')[0]){
  27. othis.prepend('<h3 class="layui-code-h3">'+ (othis.attr('lay-title')||options.title||'code') + (options.about ? '<a href="'+ about +'" target="_blank">layui.code</a>' : '') + '</h3>');
  28. }
  29. var ol = othis.find('>.layui-code-ol');
  30. othis.addClass('layui-box layui-code-view');
  31. //识别皮肤
  32. if(othis.attr('lay-skin') || options.skin){
  33. othis.addClass('layui-code-' +(othis.attr('lay-skin') || options.skin));
  34. }
  35. //按行数适配左边距
  36. if((ol.find('li').length/100|0) > 0){
  37. ol.css('margin-left', (ol.find('li').length/100|0) + 'px');
  38. }
  39. //设置最大高度
  40. if(othis.attr('lay-height') || options.height){
  41. ol.css('max-height', othis.attr('lay-height') || options.height);
  42. }
  43. });
  44. });
  45. }).addcss('modules/code.css', 'skincodecss');