| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- <?php
- namespace App\Admin\Extensions\Show;
- use Dcat\Admin\Admin;
- use Dcat\Admin\Show\AbstractField;
- use Dcat\Admin\Support\Helper;
- /**
- * Show页面复制功能
- *
- * 为Show页面的字段添加复制按钮功能
- */
- class Copyable extends AbstractField
- {
- /**
- * 添加复制功能的JavaScript脚本
- */
- protected function addScript()
- {
- $script = <<<'JS'
- $('.show-field-copyable').off('click').on('click', function (e) {
- e.preventDefault();
-
- var content = $(this).data('content');
-
- // 创建临时输入框
- var $temp = $('<input>');
- $("body").append($temp);
- $temp.val(content).select();
-
- // 执行复制
- try {
- var successful = document.execCommand('copy');
- if (successful) {
- // 显示成功提示
- Dcat.success('复制成功');
- } else {
- Dcat.error('复制失败');
- }
- } catch (err) {
- // 使用现代API作为备选方案
- if (navigator.clipboard) {
- navigator.clipboard.writeText(content).then(function() {
- Dcat.success('复制成功');
- }).catch(function() {
- Dcat.error('复制失败');
- });
- } else {
- Dcat.error('浏览器不支持复制功能');
- }
- }
-
- $temp.remove();
- });
- JS;
- Admin::script($script);
- }
- /**
- * 渲染复制按钮
- *
- * @return string
- */
- public function render()
- {
- $this->addScript();
- $value = Helper::htmlEntityEncode($this->value);
-
- if ($this->value === '' || $this->value === null) {
- return $this->value;
- }
- $html = <<<HTML
- <div class="show-field-copyable-wrapper">
- <span class="show-field-value">{$value}</span>
- <a href="javascript:void(0);"
- class="show-field-copyable text-muted ml-2"
- data-content="{$value}"
- title="点击复制">
- <i class="fa fa-copy"></i>
- </a>
- </div>
- HTML;
- return $html;
- }
- }
|