使用Greasemonkey将日期选择器添加到文本框中

时间:2012-01-04 21:47:35

标签: javascript datepicker greasemonkey

有一个文本框需要日期但没有日期选择器。我想用Greasemonkey添加一个。我找了一个例子,却找不到一个。

这可能吗?这样做有一个例子吗?它不需要花哨。

1 个答案:

答案 0 :(得分:4)

我喜欢使用jQuery UI's datepicker(),因为我通常会加载jQuery UI,而且它是相当知名/支持的。

不幸的是,datepicker功能使用了一些犯罪错误的事件代码,这需要一点点捏造才能在沙盒环境中工作。

不过,它并不太难。这是一个完整的Greasemonkey脚本:

// ==UserScript==
// @name        _Datepicker fun
// @include     http://YOUR_SERVER/YOUR_PATH/*
// @include     http://jsbin.com/ukelij*
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
// @require     https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js
// @resource    jqUI_CSS  http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css
// ==/UserScript==

//--- Date picker needs additional CSS
GM_addStyle (GM_getResourceText ("jqUI_CSS") );

//--- Add datepicker popups to select inputs:
$("#pickMe").datepicker ();
$("#pickMe").click ( function () {
    setTimeout (cleanUpCrappyEventHandling, 100);
} );

/*--- Clean up ultra-crappy event handling ('til dev team eventually fixes).
    This must be done to allow the picker to work in a sandboxed environment.
    Alternately, you can modify the jQuery-UI source ala http://stackoverflow.com/q/2855403
*/
function cleanUpCrappyEventHandling () {
    var nodesWithBadEvents  = $(
        "div.ui-datepicker td[onclick^='DP'], div.ui-datepicker a[onclick^='DP']"
    );
    nodesWithBadEvents.each ( function () {
        var jThis       = $(this);
        var fubarFunc   = jThis.attr ("onclick");

        /*--- fubarFunc will typically be like:
            DP_jQuery_1325718069430.datepicker._selectDay('#pickMe',0,2012, this);return false;
        */
        fubarFunc       = fubarFunc.replace (/return\s+\w+;/i, "");

        jThis.removeAttr ("onclick");
        jThis.click ( function () {
            eval (fubarFunc);
            cleanUpCrappyEventHandling ();
        } );
    } );
}


您可以加载此内容并针对this page at jsBin进行测试。