고수님께 스크립트 욕먹을 각오하고ㅡㅡ

고수님께 스크립트 욕먹을 각오하고ㅡㅡ

QA

고수님께 스크립트 욕먹을 각오하고ㅡㅡ

답변 4

본문

올려봅니다. 죄송합니다.

소스가 길어서,,300줄이나..유유 

문제되는 부분이 초반 중반은 아닌거 같고 후반 같습니다.

 

클립보드 복사하는 자바소스인데요,,,

이걸 리스트에 넣고 특정 text를 복사하는데...

그누 리스트의 copy라는 것과 충돌되어 undefined할 게시물 한개이상 선택하세요라고 자꾸 뜨거든요,,,

 

스크립트 소스에도 copy라는 함수가 사용되어 그러는 거 같습니다.

충돌을 피해볼까하고 copy를 copy_word로 바꿔봐도 undefined할 게시물어쩌구 자꾸뜨구요,,,

 

    var ClipboardAction = function () {

 

 

        function ClipboardAction(options) {

            _classCallCheck(this, ClipboardAction);

 

            this.resolveOptions(options);

            this.initSelection();

        }

 

 

 

 

        ClipboardAction.prototype.resolveOptions = function resolveOptions() {

            var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];

 

            this.action = options.action;

            this.emitter = options.emitter;

            this.target = options.target;

            this.text = options.text;

            this.trigger = options.trigger;

 

            this.selectedText = '';

        };

 

        ClipboardAction.prototype.initSelection = function initSelection() {

            if (this.text) {

                this.selectFake();

            } else if (this.target) {

                this.selectTarget();

            }

        };

 

        ClipboardAction.prototype.selectFake = function selectFake() {

            var _this = this;

 

            var isRTL = document.documentElement.getAttribute('dir') == 'rtl';

 

            this.removeFake();

 

            this.fakeHandlerCallback = function () {

                return _this.removeFake();

            };

            this.fakeHandler = document.body.addEventListener('click', this.fakeHandlerCallback) || true;

 

            this.fakeElem = document.createElement('textarea');

            // Prevent zooming on iOS

            this.fakeElem.style.fontSize = '12pt';

            // Reset box model

            this.fakeElem.style.border = '0';

            this.fakeElem.style.padding = '0';

            this.fakeElem.style.margin = '0';

            // Move element out of screen horizontally

            this.fakeElem.style.position = 'absolute';

            this.fakeElem.style[isRTL ? 'right' : 'left'] = '-9999px';

            // Move element to the same position vertically

            this.fakeElem.style.top = (window.pageYOffset || document.documentElement.scrollTop) + 'px';

            this.fakeElem.setAttribute('readonly', '');

            this.fakeElem.value = this.text;

 

            document.body.appendChild(this.fakeElem);

 

            this.selectedText = (0, _select2.default)(this.fakeElem);

            this.copy_wordText();

        };

 

        ClipboardAction.prototype.removeFake = function removeFake() {

            if (this.fakeHandler) {

                document.body.removeEventListener('click', this.fakeHandlerCallback);

                this.fakeHandler = null;

                this.fakeHandlerCallback = null;

            }

 

            if (this.fakeElem) {

                document.body.removeChild(this.fakeElem);

                this.fakeElem = null;

            }

        };

 

        ClipboardAction.prototype.selectTarget = function selectTarget() {

            this.selectedText = (0, _select2.default)(this.target);

            this.copy_wordText();

        };

 

        ClipboardAction.prototype.copy_wordText = function copy_wordText() {

            var succeeded = undefined;

 

            try {

                succeeded = document.execCommand(this.action);

            } catch (err) {

                succeeded = false;

            }

 

            this.handleResult(succeeded);

        };

 

        ClipboardAction.prototype.handleResult = function handleResult(succeeded) {

            if (succeeded) {

                this.emitter.emit('success', {

                    action: this.action,

                    text: this.selectedText,

                    trigger: this.trigger,

                    clearSelection: this.clearSelection.bind(this)

                });

            } else {

                this.emitter.emit('error', {

                    action: this.action,

                    trigger: this.trigger,

                    clearSelection: this.clearSelection.bind(this)

                });

            }

        };

 

        ClipboardAction.prototype.clearSelection = function clearSelection() {

            if (this.target) {

                this.target.blur();

            }

 

            window.getSelection().removeAllRanges();

        };

 

        ClipboardAction.prototype.destroy = function destroy() {

            this.removeFake();

        };

 

        _createClass(ClipboardAction, [{

            key: 'action',

            set: function set() {

                var action = arguments.length <= 0 || arguments[0] === undefined ? 'copy_word' : arguments[0];

 

                this._action = action;

 

                if (this._action !== 'copy_word' && this._action !== 'cut') {

                    throw new Error('Invalid "action" value, use either "copy_word" or "cut"');

                }

            },

            get: function get() {

                return this._action;

            }

        }, {

            key: 'target',

            set: function set(target) {

                if (target !== undefined) {

                    if (target && (typeof target === 'undefined' ? 'undefined' : _typeof(target)) === 'object' && target.nodeType === 1) {

                        if (this.action === 'copy_word' && target.hasAttribute('disabled')) {

                            throw new Error('Invalid "target" attribute. Please use "readonly" instead of "disabled" attribute');

                        }

 

                        if (this.action === 'cut' && (target.hasAttribute('readonly') || target.hasAttribute('disabled'))) {

                            throw new Error('Invalid "target" attribute. You can\'t cut text from elements with "readonly" or "disabled" attributes');

                        }

 

                        this._target = target;

                    } else {

                        throw new Error('Invalid "target" value, use a valid Element');

                    }

                }

            },

            get: function get() {

                return this._target;

            }

        }]);

 

        return ClipboardAction;

    }();

 

    module.exports = ClipboardAction;

});

 

},{"select":6}],9:[function(require,module,exports){

(function (global, factory) {

    if (typeof define === "function" && define.amd) {

        define(['module', './clipboard-action', 'tiny-emitter', 'good-listener'], factory);

    } else if (typeof exports !== "undefined") {

        factory(module, require('./clipboard-action'), require('tiny-emitter'), require('good-listener'));

    } else {

        var mod = {

            exports: {}

        };

        factory(mod, global.clipboardAction, global.tinyEmitter, global.goodListener);

        global.clipboard = mod.exports;

    }

})(this, function (module, _clipboardAction, _tinyEmitter, _goodListener) {

    'use strict';

 

    var _clipboardAction2 = _interopRequireDefault(_clipboardAction);

 

    var _tinyEmitter2 = _interopRequireDefault(_tinyEmitter);

 

    var _goodListener2 = _interopRequireDefault(_goodListener);

 

    function _interopRequireDefault(obj) {

        return obj && obj.__esModule ? obj : {

            default: obj

        };

    }

 

    function _classCallCheck(instance, Constructor) {

        if (!(instance instanceof Constructor)) {

            throw new TypeError("Cannot call a class as a function");

        }

    }

 

    function _possibleConstructorReturn(self, call) {

        if (!self) {

            throw new ReferenceError("this hasn't been initialised - super() hasn't been called");

        }

 

        return call && (typeof call === "object" || typeof call === "function") ? call : self;

    }

 

    function _inherits(subClass, superClass) {

        if (typeof superClass !== "function" && superClass !== null) {

            throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);

        }

 

        subClass.prototype = Object.create(superClass && superClass.prototype, {

            constructor: {

                value: subClass,

                enumerable: false,

                writable: true,

                configurable: true

            }

        });

        if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;

    }

 

    var Clipboard = function (_Emitter) {

        _inherits(Clipboard, _Emitter);

 

 

 

        function Clipboard(trigger, options) {

            _classCallCheck(this, Clipboard);

 

            var _this = _possibleConstructorReturn(this, _Emitter.call(this));

 

            _this.resolveOptions(options);

            _this.listenClick(trigger);

            return _this;

        }

 

 

 

 

        Clipboard.prototype.resolveOptions = function resolveOptions() {

            var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];

 

            this.action = typeof options.action === 'function' ? options.action : this.defaultAction;

            this.target = typeof options.target === 'function' ? options.target : this.defaultTarget;

            this.text = typeof options.text === 'function' ? options.text : this.defaultText;

        };

 

        Clipboard.prototype.listenClick = function listenClick(trigger) {

            var _this2 = this;

 

            this.listener = (0, _goodListener2.default)(trigger, 'click', function (e) {

                return _this2.onClick(e);

            });

        };

 

        Clipboard.prototype.onClick = function onClick(e) {

            var trigger = e.delegateTarget || e.currentTarget;

 

            if (this.clipboardAction) {

                this.clipboardAction = null;

            }

 

            this.clipboardAction = new _clipboardAction2.default({

                action: this.action(trigger),

                target: this.target(trigger),

                text: this.text(trigger),

                trigger: trigger,

                emitter: this

            });

        };

 

        Clipboard.prototype.defaultAction = function defaultAction(trigger) {

            return getAttributeValue('action', trigger);

        };

 

        Clipboard.prototype.defaultTarget = function defaultTarget(trigger) {

            var selector = getAttributeValue('target', trigger);

 

            if (selector) {

                return document.querySelector(selector);

            }

        };

 

        Clipboard.prototype.defaultText = function defaultText(trigger) {

            return getAttributeValue('text', trigger);

        };

 

        Clipboard.prototype.destroy = function destroy() {

            this.listener.destroy();

 

            if (this.clipboardAction) {

                this.clipboardAction.destroy();

                this.clipboardAction = null;

            }

        };

 

        return Clipboard;

    }(_tinyEmitter2.default);

 

 

    function getAttributeValue(suffix, element) {

        var attribute = 'data-clipboard-' + suffix;

 

        if (!element.hasAttribute(attribute)) {

            return;

        }

 

        return element.getAttribute(attribute);

    }

 

    module.exports = Clipboard;

});

 

},{"./clipboard-action":8,"good-listener":4,"tiny-emitter":7}]},{},[9])(9)

 

});

이 질문에 댓글 쓰기 :

답변 4

NPM 설치 안하고 그냥 다운받으면 됩니다.

 

node js 패키지 관리자일 뿐입니다. github 에서 다운 받으면 됩니다.

 

https://github.com/zenorocha/clipboard.js

 

우측에 Clone or download 하세요.

 

js 로드 후에

 

 

<!-- Target --> <input id="foo" value="https://github.com/zenorocha/clipboard.js.git"> --> 복사할 대상에 ID값 주기 <!-- Trigger --> <button class="btn" data-clipboard-target="#foo"> --> HTML5 Data attribute 에 #foo 아이디 지정 <img src="assets/clippy.svg" alt="Copy to clipboard"> </button>

 

처럼 하세요. 사이트에 설명 다 있는데요 ????????????????????????????????????????

 

Setup

First, include the script located on the dist folder or load it from a third-party CDN provider.

<script src="dist/clipboard.min.js"></script>

Now, you need to instantiate it by passing a DOM selector,HTML element, or list of HTML elements.

new Clipboard('.btn');

Internally, we need to fetch all elements that matches with your selector and attach event listeners for each one. But guess what? If you have hundreds of matches, this operation can consume a lot of memory.

For this reason we use event delegation which replaces multiple event listeners with just a single listener. After all, #perfmatters.


바쁘신 시간에 감사합니다.

수업시간에 배운 영어를 참고하여,,

리스트페이지에 이렇게 했구요,

    <script src="../js/clipboard.min.js"></script>  //다운받아 js폴더에 넣음

리스트페이지에
    <script>
    var clipboard = new Clipboard(".btn");
 
    clipboard.on("success", function(e) {
        console.log(e);
    });

    clipboard.on("error", function(e) {
        console.log(e);
    });
   
   
    </script>

복사할 대상에
<button class="btn" id="wr_25" data-clipboard-text="<?=$list[$i][wr_25]?>">COPY</button>

이렇게 했는데 애러가 떠서 질문드린겁니다.

복사는 되는데 undefined할 대상을 한개이상 선택하라고 자꾸 얼럿이 떠서요...

clipboard.min.js가 그누의 선택복사버튼의 copy 함수?도 작동시켜서 이런 애러가 나오는거 같습니다.

module.exports = ~~

require()~~

이런 코드들이 있는것을 보니, Node.js 인거 같은데...

node.js 는 서버용 자바스크립트 언어입니다.

웹브라우저에서 작동하는 일반 자바스크립트가 아닙니다.

웹브라우저에서 작동하는 자바스크립트를, 서버에서도 자바스크립트를 사용가능하게 하자...

이래서 개발한것이 node.js입니다.(즉, php 같은거죠..) 

php로 서버측 개발하는 것과 같이, node.js도 같은 용도로 만들어진 언어이죠..

그누보드의 개발언어가 php이듯이, 누군가가 그누보드를 node.js라는 언어로 개발한다고 하면...

그누보드 설치환경은, php + mysql / node.js + mysql 동시지원...

뭐..이런 멘트가 되는거죠...

즉시 체포하시는 군요~

https://clipboardjs.com/ 이거 인데...지금 보니

You can get it on npm.
Copy to clipboard
npm install clipboard --save
설치하라고 되어 있군요,,

그냥 자바스크립트인줄 알았어요,,
.js라고 되어 있어서..

npm설치를 공부해야 하는군요,,휴


감사합니다.

https://clipboardjs.com/

 

이걸 추천합니다. 


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
 
<textarea id="sandbox" style="height:0px; width:0px;"></textarea>
<div id="aa">무궁화 꽃이 피었습니다~</div>
<button id="btn_copy">클립보드로 복사하기</button>
 
<script>
$('#btn_copy').click(function(){
    var copy_text = $('#aa').text();
 
    var copyFrom = $('textarea#sandbox');
    copyFrom.text( copy_text );
    copyFrom.select();
    document.execCommand('copy');
});
</script>

 

답변을 작성하시기 전에 로그인 해주세요.
QA 내용 검색
질문등록
filter #php ×
전체 15,331
© SIRSOFT
현재 페이지 제일 처음으로