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

来源:互联网 发布:windows模块安装程序 编辑:程序博客网 时间:2024/06/05 11:00

先上图


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