饥人谷技术博客让前端飞

Input length limitation (Vue自定义

2017-08-28  本文已影响0人  小罗程序员

记录一下vue.js 自定义指令 -- 输入框字数长度限制

//css
.valLengthCounter {
    position: absolute;
    right: 5px;
    font-size: 12px;
    color: #888;
    display: none;
}
//JavaScript
Vue.directive('limitation', {
    bind: function(el, binding) {
    },
    inserted: function(el, binding) {
        $(el).css('transition',' all 0.3s')
        $(el).css('width',' 100%')
        var counter = $("<span class='valLengthCounter '></span>")
        $(el).attr('maxlength', binding.value)
        $(el).parent('div').css({
            'position': 'relative',
            'display': 'flex',
            'align-items': 'center',
            'justify-content': 'space-between'
        })
        $(el).parent('div').append(counter)
        $(el).siblings('.valLengthCounter').text($(el).val().length + '/' + binding.value)
        el.addEventListener('keyup', function() {
            curLength = $(el).val().length
            $(el).siblings('.valLengthCounter').text($(el).val().length + '/' + binding.value)
        })
        el.addEventListener("focus", function() {
            $(el).siblings('.valLengthCounter').fadeIn(300)
                // cleaner.css('right', counter.width() + 30)
            $(el).css('paddingRight', $(el).siblings('.valLengthCounter').width() + 20)
        })
        el.addEventListener("blur", function() {
            $(el).siblings('.valLengthCounter').fadeOut(300)
                // cleaner.css('right', 5)
            $(el).css('paddingRight', 0)
        })
    }
})
上一篇下一篇

猜你喜欢

热点阅读