autosize外掛和自動增刪行

石头记1發表於2024-07-22

http://www.jacklmoore.com/autosize/

https://github.com/jackmoore/autosize?tab=readme-ov-file

列表空值自動刪行,末行輸入,底部自動增行,不超過10行,textarea文字域自動高度沒有捲軸

<div id="app" v-cloak>
    <table style="width:700px;">
        <tr v-for="(item,index) in list" :key="index">
            <td style="width:40%;">
                <textarea type="text" class="textaa" v-model="item.Q.XMNR" v-on:input="ltextFn($event,item,index)" v-on:focus="zenghFn"></textarea>
            </td>
            <td style="width:20%;text-align: center;">--</td>
            <td style="width:40%;">
                <textarea type="text" class="textaa" v-model="item.H.XMNR" v-on:input="rtextFn($event,item,index)" v-on:focus="zenghFn"></textarea>
            </td>
        </tr>
    </table>
</div>
<!-- <script src="http://www.h5al.cn/js/autosize.min.js"></script> -->
<script src="http://www.h5al.cn/js/vue2716.js"></script>
<script src="http://www.h5al.cn/js/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
var vm = new Vue({
    el:"#app",
    data:{
        list:[]
    },
    created(){
        this.getData()
    },
    methods:{
        getData(){
            var self = this
            var ary = [
                {
                    Q:{XMNR: '抓改革、促發展,歸根到底就是為了讓人民過上更好的日子。',LX: 1,DDID : 1},
                    H:{XMNR: '十八大以來,為核心的堅持以人民為中心推進改革,',LX: 2,DDID : 2}
                },
                {
                    Q:{XMNR: '始終把人民利益擺在至高無上的地位,抓住人民最關心最直接最現實的利益問題推進重點領域改革。',LX: 1,DDID : 3},
                    H:{XMNR: '二十屆三中全會審議透過的《中共中央關於進一步全面深化改革、推進中國式現代化的決定》,',LX: 2,DDID : 4}
                },
                {
                    Q:{XMNR: '堅持人民至上,從人民整體利益、根本利益、長遠利益出發謀劃和推進改革,',LX: 1,DDID : 5},
                    H:{XMNR: '充分彰顯了我們宗旨、初心使命,充分體現了新時代思想的世界觀和方法論。',LX: 2,DDID : 6}
                }
            ]
            if(ary.length!=0){
                $.each(ary,function(index,item){
                    item.uid = index+1
                })
                self.list = ary
            }else{
                self.list = [{
                    Q:{DDID:'',LX:1,XMNR:''},
                    H:{DDID:'',LX:2,XMNR:''},
                    uid:1,
                }]
            }     
            this.zenghFn()
        },
        ltextFn(event,item,ind){
            var self = this
            var curval = event.target.value
            var num = item.uid;
            if(curval === '' && (item.H.XMNR === '' || item.H.XMNR === null)){
                if(self.list.length == 1){
                    // alert("該行不能刪除!!");
                    return false;
                }else{
                    for(var i=0;i < self.list.length;i++){
                        if(self.list[i].uid == num){
                            self.list.splice(i,1);
                            setTimeout(function(){
                                var ta = document.querySelectorAll('textarea');
                                $.each(ta,function(index,item){
                                    autosize.update(item);
                                })
                            },500)
                            break;
                        }
                    }
                }
            }else{
                this.zenghFn()
            }
            // console.log(self.list);
        },
        rtextFn(event,item,ind){
            var self = this
            var curval = event.target.value
            var num = item.uid;
            if((item.Q.XMNR === '' || item.Q.XMNR === null) && curval === ''){
                if(self.list.length == 1){
                    // alert("該行不能刪除!!");
                    return false;
                }else{
                    for(var i=0;i < self.list.length;i++){
                        if(self.list[i].uid == num){
                            self.list.splice(i,1);
                            setTimeout(function(){
                                var ta = document.querySelectorAll('textarea');
                                $.each(ta,function(index,item){
                                    autosize.update(item);
                                })
                            },500)
                            break;
                        }
                    }
                }
            }else{
                this.zenghFn()
            }
            // console.log(self.list);
        },
        zenghFn(){
            var self = this
            var xobj = {}
            if(self.list.length < 10){
                var obj = self.list[self.list.length-1]
                if(obj.Q.XMNR != '' || obj.H.XMNR != ''){
                    xobj.Q = {}
                    xobj.H = {}
                    xobj.Q.XMNR = ''
                    xobj.Q.LX = 1
                    xobj.Q.DDID = ''
                    xobj.H.XMNR = ''
                    xobj.H.LX = 2
                    xobj.H.DDID = ''
                    xobj.uid = self.list.length + 1
                    self.list.push(xobj)
                    setTimeout(function(){
                        autosize(document.querySelectorAll('textarea'));
                    },500)
                }
            }
            // console.log(self.list);
        },
    }
})

;(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
        typeof define === 'function' && define.amd ? define(factory) :
            (global = global || self, global.autosize = factory());
}(this, (function () {
    var assignedElements = new Map();
    function assign(ta) {
        if (!ta || !ta.nodeName || ta.nodeName !== 'TEXTAREA' || assignedElements.has(ta)) return;
        var previousHeight = null;
        function cacheScrollTops(el) {
            var arr = [];
            while (el && el.parentNode && el.parentNode instanceof Element) {
                if (el.parentNode.scrollTop) {
                    arr.push([el.parentNode, el.parentNode.scrollTop]);
                }
                el = el.parentNode;
            }
            return function () {
                return arr.forEach(function (_ref) {
                    var node = _ref[0],
                        scrollTop = _ref[1];
                    node.style.scrollBehavior = 'auto';
                    node.scrollTop = scrollTop;
                    node.style.scrollBehavior = null;
                });
            };
        }
        var computed = window.getComputedStyle(ta);
        function setHeight(_ref2) {
            var _ref2$restoreTextAlig = _ref2.restoreTextAlign,
                restoreTextAlign = _ref2$restoreTextAlig === void 0 ? null : _ref2$restoreTextAlig,
                _ref2$testForHeightRe = _ref2.testForHeightReduction,
                testForHeightReduction = _ref2$testForHeightRe === void 0 ? true : _ref2$testForHeightRe;
            var initialOverflowY = computed.overflowY;
            if (ta.scrollHeight === 0) {
                // If the scrollHeight is 0, then the element probably has display:none or is detached from the DOM.
                return;
            } // disallow vertical resizing
            if (computed.resize === 'vertical') {
                ta.style.resize = 'none';
            } else if (computed.resize === 'both') {
                ta.style.resize = 'horizontal';
            }
            var restoreScrollTops; // remove inline height style to accurately measure situations where the textarea should shrink
            // however, skip this step if the new value appends to the previous value, as textarea height should only have grown
            if (testForHeightReduction) {
                // ensure the scrollTop values of parent elements are not modified as a consequence of shrinking the textarea height
                restoreScrollTops = cacheScrollTops(ta);
                ta.style.height = '';
            }
            var newHeight;
            if (computed.boxSizing === 'content-box') {
                newHeight = ta.scrollHeight - (parseFloat(computed.paddingTop) + parseFloat(computed.paddingBottom));
            } else {
                newHeight = ta.scrollHeight + parseFloat(computed.borderTopWidth) + parseFloat(computed.borderBottomWidth);
            }
            if (computed.maxHeight !== 'none' && newHeight > parseFloat(computed.maxHeight)) {
                if (computed.overflowY === 'hidden') {
                    ta.style.overflow = 'scroll';
                }
                newHeight = parseFloat(computed.maxHeight);
            } else if (computed.overflowY !== 'hidden') {
                ta.style.overflow = 'hidden';
            }
            ta.style.height = newHeight + 'px';
            if (restoreTextAlign) {
                ta.style.textAlign = restoreTextAlign;
            }
            if (restoreScrollTops) {
                restoreScrollTops();
            }
            if (previousHeight !== newHeight) {
                ta.dispatchEvent(new Event('autosize:resized', {
                    bubbles: true
                }));
                previousHeight = newHeight;
            }
            if (initialOverflowY !== computed.overflow && !restoreTextAlign) {
                var textAlign = computed.textAlign;
                if (computed.overflow === 'hidden') {
                    // Webkit fails to reflow text after overflow is hidden,
                    // even if hiding overflow would allow text to fit more compactly.
                    // The following is intended to force the necessary text reflow.
                    ta.style.textAlign = textAlign === 'start' ? 'end' : 'start';
                }
                setHeight({
                    restoreTextAlign: textAlign,
                    testForHeightReduction: true
                });
            }
        }
        function fullSetHeight() {
            setHeight({
                testForHeightReduction: true,
                restoreTextAlign: null
            });
        }
        var handleInput = function () {
            var previousValue = ta.value;
            return function () {
                setHeight({
                    // if previousValue is '', check for height shrinkage because the placeholder may be taking up space instead
                    // if new value is merely appending to previous value, skip checking for height deduction
                    testForHeightReduction: previousValue === '' || !ta.value.startsWith(previousValue),
                    restoreTextAlign: null
                });
                previousValue = ta.value;
            };
        }();
        var destroy = function (style) {
            ta.removeEventListener('autosize:destroy', destroy);
            ta.removeEventListener('autosize:update', fullSetHeight);
            ta.removeEventListener('input', handleInput);
            window.removeEventListener('resize', fullSetHeight); // future todo: consider replacing with ResizeObserver
            Object.keys(style).forEach(function (key) {
                return ta.style[key] = style[key];
            });
            assignedElements["delete"](ta);
        }.bind(ta, {
            height: ta.style.height,
            resize: ta.style.resize,
            textAlign: ta.style.textAlign,
            overflowY: ta.style.overflowY,
            overflowX: ta.style.overflowX,
            wordWrap: ta.style.wordWrap
        });
        ta.addEventListener('autosize:destroy', destroy);
        ta.addEventListener('autosize:update', fullSetHeight);
        ta.addEventListener('input', handleInput);
        window.addEventListener('resize', fullSetHeight); // future todo: consider replacing with ResizeObserver
        ta.style.overflowX = 'hidden';
        ta.style.wordWrap = 'break-word';
        assignedElements.set(ta, {
            destroy: destroy,
            update: fullSetHeight
        });
        fullSetHeight();
    }
    function destroy(ta) {
        var methods = assignedElements.get(ta);

        if (methods) {
            methods.destroy();
        }
    }
    function update(ta) {
        var methods = assignedElements.get(ta);

        if (methods) {
            methods.update();
        }
    }
    var autosize = null; // Do nothing in Node.js environment
    if (typeof window === 'undefined') {
        autosize = function autosize(el) {
            return el;
        };
        autosize.destroy = function (el) {
            return el;
        };
        autosize.update = function (el) {
            return el;
        };
    } else {
        autosize = function autosize(el, options) {
            if (el) {
                Array.prototype.forEach.call(el.length ? el : [el], function (x) {
                    return assign(x);
                });
            }
            return el;
        };
        autosize.destroy = function (el) {
            if (el) {
                Array.prototype.forEach.call(el.length ? el : [el], destroy);
            }
            return el;
        };
        autosize.update = function (el) {
            if (el) {
                Array.prototype.forEach.call(el.length ? el : [el], update);
            }
            return el;
        };
    }
    var autosize$1 = autosize;
    return autosize$1;
})));

setTimeout(function(){
    autosize(document.querySelectorAll('textarea'));
},500)
</script>

相關文章