[jQuery][插件]重置文本框值的小按钮

先上图


Demo

HTML

这个插件没有任何样式,所以需要自己写把样式写好

<div class="container">
    <p>
        <input id="username" type="text" placeholder="This is Test" />
        <span data-target="username">&times;</span>
    </p>
    <p>
        <input id="password" type="text" placeholder="Nothing" />
        <span data-target="password">&times;</span>
    </p>
</div>

CSS

样式完全是自己定义

body {
  padding: 20px;
}
p {
  position: relative;
  width: 200px;
  padding: 5px;
  border: 1px solid lightgray;
}
p input {
  display: inline-block;
  width: 100%;
  font-size: 1em;
  border: none;
  outline: none;
}
p span {
  position: absolute;
  top: 50%;
  right: 2em;
  margin-top: -11px;
  display: inline-block;
  padding: 0 .5em;
  border-radius: 50%;
  font-weight: bold;
  color: white;
  background-color: lightgray;
  cursor: pointer;
}

JS

这算是初次写插件吧(这也算插件?-。-)
不知道这样的写法规不规范,希望大家能指正。

+function ($, window, document, undefined) {
    var reset = function (ele, opt) {
        this.$element = $(ele),
        this.$target = null,
        this.defaults = {
            'value': '',
            'autohide': true,
            'target': '',
        },
        this.options = $.extend({}, this.defaults, opt);
    }
    $.fn.btnReset = function (options) {
        var btn = new reset(this, options);
        btn.$target = $('#' + btn.options.target);
        btn.$element.click(function () {
            btn.$target.val(btn.options.value);
            if (btn.options.autohide) {
                btn.$element.hide();
            }
        });
        if (btn.options.autohide) {
            btn.$element.hide();
            btn.$target.keyup(function () {
                btn.$element.show();
            });
        }
        return btn;
    }
}(jQuery, window, document);

调用方法

首先引入相关js
然后就是调用 btnReset 方法了

<script>
    $(document).ready(function () {
        $("span").each(function () {
            $(this).btnReset({
                'target': $(this).data('target'),
            });
        });
    });
</script>

参数说明

target

输入框的id,必须!

value

点击按钮之后设定的值,默认为空字符串''

autoHide

按钮是否自动隐藏,默认为true

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值