Copyable.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. namespace App\Admin\Extensions\Show;
  3. use Dcat\Admin\Admin;
  4. use Dcat\Admin\Show\AbstractField;
  5. use Dcat\Admin\Support\Helper;
  6. /**
  7. * Show页面复制功能
  8. *
  9. * 为Show页面的字段添加复制按钮功能
  10. */
  11. class Copyable extends AbstractField
  12. {
  13. /**
  14. * 添加复制功能的JavaScript脚本
  15. */
  16. protected function addScript()
  17. {
  18. $script = <<<'JS'
  19. $('.show-field-copyable').off('click').on('click', function (e) {
  20. e.preventDefault();
  21. var content = $(this).data('content');
  22. // 创建临时输入框
  23. var $temp = $('<input>');
  24. $("body").append($temp);
  25. $temp.val(content).select();
  26. // 执行复制
  27. try {
  28. var successful = document.execCommand('copy');
  29. if (successful) {
  30. // 显示成功提示
  31. Dcat.success('复制成功');
  32. } else {
  33. Dcat.error('复制失败');
  34. }
  35. } catch (err) {
  36. // 使用现代API作为备选方案
  37. if (navigator.clipboard) {
  38. navigator.clipboard.writeText(content).then(function() {
  39. Dcat.success('复制成功');
  40. }).catch(function() {
  41. Dcat.error('复制失败');
  42. });
  43. } else {
  44. Dcat.error('浏览器不支持复制功能');
  45. }
  46. }
  47. $temp.remove();
  48. });
  49. JS;
  50. Admin::script($script);
  51. }
  52. /**
  53. * 渲染复制按钮
  54. *
  55. * @return string
  56. */
  57. public function render()
  58. {
  59. $this->addScript();
  60. $value = Helper::htmlEntityEncode($this->value);
  61. if ($this->value === '' || $this->value === null) {
  62. return $this->value;
  63. }
  64. $html = <<<HTML
  65. <div class="show-field-copyable-wrapper">
  66. <span class="show-field-value">{$value}</span>
  67. <a href="javascript:void(0);"
  68. class="show-field-copyable text-muted ml-2"
  69. data-content="{$value}"
  70. title="点击复制">
  71. <i class="fa fa-copy"></i>
  72. </a>
  73. </div>
  74. HTML;
  75. return $html;
  76. }
  77. }