jQuery Datepicker - 在悬停时获取日期

时间:2014-05-21 02:19:01

标签: javascript jquery datepicker hover

我正在使用this jQuery datepicker,我正试图在悬停时获取日期的值。我看到插件有一个参数:

eventName The desired event to trigger the date picker. Default: 'click'

由于文档非常有限,我想知道除了点击之外是否还有其他选项,如果没有,我如何使用eventName获取悬停值。

9 个答案:

答案 0 :(得分:12)

eventName选项仅用于将内部show方法绑定到事件:

$(this).bind(options.eventName, show);

理论上,您可以使用hover来显示日期选择器,但您必须为'mouseenter mouseleave'选项指定eventName,因为hover是一个jQuery绑定到'mouseenter mouseleave'的快捷方法。

由于您已(在评论中)表明您希望在kayak.co.in找到行为,因此您只需在mouseenter电话后链接.DatePicker处理程序即可模仿此情况(其他任何事情都不需要改变):

$('#date').DatePicker({
    // options...
}).on('mouseenter', '.datepickerDays td:not(.datepickerDisabled, .datepickerNotInMonth)', function (e) { // delegating on the mouseenter event which jQuery patches to be a cross-browser event, and only targeting clickable dates
    var target = $(this).children('a'), // cache lookup
        options = target.parents('.datepicker').data('datepicker'), // get DatePicker options
        current = new Date(options.current), // grab the current month/year
        val = parseInt(target.text(), 10), // grab the target date
        hoverVal = new Date(current.getFullYear(), current.getMonth(), val), // make into an actual date
        hoverDay = hoverVal.getDayName(), // get the short day name
        hoverM = hoverVal.getMonth() + 1, // and month
        hoverD = hoverVal.getDate(), // and date
        hoverText = hoverDay + ' ' + (hoverD < 10 ? '0' + hoverD : hoverD) + '/' + hoverM, // for a formatted text value
        selectedVal = new Date(options.date[0]), // get the selected date (which may just be the initial date without an actual selection or an actual selected date, hereafter "selected")
        selectedDay = selectedVal.getDayName(), // get the short day name
        selectedM = selectedVal.getMonth() + 1, // and month
        selectedD = selectedVal.getDate(), // and date
        selText = selectedDay + ' ' + (selectedD < 10 ? '0' + selectedD : selectedD) + '/' + selectedM, // for a formatted text value
        startDate = $('#startDate').data('lastHovered') || new Date(hoverVal) || selectedVal, // default to: last hovered, current hover, or "selected" date (in that order)
        endDate = $('#endDate').data('lastHovered') || new Date(options.date[1]) || startDate, // default to: last hovered, actual selected date, or "selected" date (in that order)
        startDateSelected = $('#startDate').data('startDateSelected') || $('.datepickerDays .datepickerSelected.first').length > 0, // test whether an actual date was selected
        endDateSelected = !isNaN(options.date[1]) && (options.date[1] - options.date[0] > 86400000), // test whether an end date was selected. end date is set in options when start date is actually selected and is the same day as the selected start date but the time is set to 23:59:59
        selector; // variable to store a selector string
    // no end date has been selectd AND if no start date has been selected, or if it has and the user is hovering over an earlier date, or if the user hasn't selected a date yet
    if (!endDateSelected && (!startDateSelected || (startDateSelected && hoverVal < selectedVal) || hoverVal <= startDate)) {
        selector = '#startDate'; // use the startDate input
        $('#endDate').val(''); // since using startDate, endDate has not been selected. make sure the input is cleared.
    } else if (!endDateSelected){ // otherwise, as long as no end date has been selected
        selector = '#endDate'; // use the endDate input
        $('#startDate').val(selText); // and set the value of startDate back to the actual selected date value
    }
    if (!endDateSelected) { // if the user hasn't picked an end date (which cannot be picked without a start date)
        $(selector).data({ // persist the last hovered date and whether a start date has been selected
            "lastHovered": hoverVal,
            "startDateSelected": startDateSelected // this is necessary as the plugin routinely destroys and recreates the tables that make up the calendars while navigating the calendars
        }).val(hoverText); // set the value of the input to the hovered date
    }
});

工作演示:http://jsfiddle.net/QgXNn/5/

答案 1 :(得分:3)

尝试这种方法:

为您的悬停目标创建一个Div

<div id="content">
    <div id="test">Hover Me</div>
    <div id="datePicker"></div>
</div>

准备好后,初始化并绑定到悬停事件以打开

$(function () {
    $('#datePicker').datepicker();
    $('#datePicker').hide();

    $('#content').hover(function () {
        $('#datePicker').fadeIn('fast');
    }, function () {
        $('#datePicker').fadeOut('fast');
    });

});

Fiddle(无法引用您的选择器,因此我使用了JQuery UI)


更新:查看新的 Fiddle

我将我的方法应用于你的小提琴。现在,当您将鼠标悬停在“Hover Me”上时,会出现您的DatePicker,并在光标离开时消失。我补充说:

$(function () {
    $('#date').hide();
    $('#test').hover(function () {
        $('#date').show();
    }, function () {
        $('#date').hide();
    });

});

-

顺便说一下,我让DatePicker对话框在非悬停时消失,只是为了效果。通过删除相邻的

可以很容易地改变它
}, function () {
    $('#date').hide();

答案 2 :(得分:3)

查看您的已修改 working fiddle here

// setting the value of the input field to hovered date
// Note that we're not triggering the "click" event bec. 
// it will cause the onChange event of the datepicker to be fired. 
// Instead, we're setting and resetting the input field value 
$("body").on("mouseover", ".datepickerDays td", function (e) {
    var d = parseInt($(this).text(), 10),
        my = $(this).closest('table').find('.datepickerMonth span').html().split(', '),
        m = $.inArray(my[0], MONTH_NAMES),
        y = parseInt(my[1], 10),
        date = new Date(y, m, d),
        textbox = $('#startDate').hasClass('focus') ? $('#endDate') : $('#startDate');
    textbox.val(getFormattedDate(date));
});

// We set back the input field back to its original value on mouseout
$("body").on("mouseout", ".datepickerDays td", function (e) {
    var fd = $('#date').DatePickerGetDate(false),
        start = getFormattedDate(fd[0]),
        end = getFormattedDate(fd[1]);
    $('#startDate').val(start);
    $('#endDate').val(end);
});

// ----------------------------------------
// HELPER FUNCTIONS & VARS
// ----------------------------------------

var MONTH_NAMES = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
    WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
function pad0(num) { return num < 10 ? '0' + num : num; }
function getFormattedDate(date) {
    if (isNaN(date.getTime())) { return ''; }
    var wd = WEEKDAYS[date.getDay()].substr(0, 3);
    return wd + ' ' + pad0(date.getDate()) + '/' + pad0(date.getMonth() + 1);
}

答案 3 :(得分:1)

对于你的问题。我想你不希望在悬停时显示日期选择器,但希望在悬停时输入框中显示值或日期。 如果你想在悬停时显示日期选择器,请尝试使用'mouseover'作为插件的eventName属性 喜欢这个

$('.inputDate').DatePicker({
    eventName:'mouseover', // This is the event to fire.
    format:'m/d/Y',
    date: $('#inputDate').val(),
    current: $('#inputDate').val(),
    starts: 1,
    position: 'right'});

它没有抓住悬停的jquery事件。

现在,当日期选择器元素悬停时,在输入标记中显示新日期。您可能需要调整插件本身尝试找到这一行734.代码是

var cal = $(tpl.wrapper).attr('id', id).bind('click', click).data('datepicker', options);

将其更改为

var cal = $(tpl.wrapper).attr('id', id).bind('mouseover', click).data('datepicker', options);

正如您所看到的,我使用了旧的mouseover事件而不是jquery的'Hover'关键字。 如果这样可行,您还可以尝试在插件中添加一个新的选项参数,例如'callon:click',并在调用时将其设置为此选项并将其传递给此行734.

var cal = $(tpl.wrapper).attr('id', id).bind(options.callon, click).data('datepicker', options);

使用此功能,您可以设置自己的事件以调用更新文本框的值。 它肯定适用于单个日期选择器。请尝试并对此发表评论。但是你可能还需要操纵更多来设置点击日期。

答案 4 :(得分:1)

由于插件已经绑定change上的click函数,我们可以通过附加hover的事件并简单地触发它来使用它。如下所示:

function make_hover(){
    $(".datepickerDays td span").hover(function(e){
        $(this).trigger("click")
    })
    $(".datepickerDays td").mouseup(function(e){
        $('#inputDate').DatePickerHide(); //hide it when click actually occurs
    })
    $(".datepickerContainer").mouseup(function(e){
        setTimeout(function(){
          make_hover()
        },0) //have to run this with setTimeout to force it to run after DOM changes
    })
}

var date=$('#inputDate').DatePicker({
    format:'m/d/Y', 
    date: $('#inputDate').val(),
    current: $('#inputDate').val(),
    eventName: 'mouseenter',
    onBeforeShow: function(){
        $('#inputDate').DatePickerSetDate($('#inputDate').val(), true);
        make_hover()
    },
    onChange: function(formated, dates){
        $('#inputDate').val(formated);
        make_hover()
    }
})

Example

答案 5 :(得分:0)

使用jQuery和jQuery UI:

<div id="date_div">
     <input type="text" id="test" placeholder="Hover Me"/>
    <div id="datePicker"></div>
</div>

<script>
jQuery(function($) {
    $('#datePicker').datepicker({
       onSelect: function(dat){
          $('#test').val(dat);
       }
    });
    $('#datePicker').hide();

    $('#date_div').hover(function(){
         $('#datePicker').fadeIn(200);
    }, function() {
         $('#datePicker').fadeOut(200);
    });
});
</script>

检查演示@:http://jsfiddle.net/renishar/ZVf48/4/

还包括jQuery和jQuery UI库..

答案 6 :(得分:0)

您可以使用委托悬停日期元素,如果是,则强制单击元素本身。

代码:

$("body").delegate(".datepickerDays td span","hover",function(e){
    $(this).click();
})

由于我不能让插件适用于较新版本的jQuery,我必须使用delegate

演示:http://jsfiddle.net/IrvinDominin/fFc7h/

答案 7 :(得分:0)

使用eventName&#39;鼠标悬停&#39;而不是&#39; hover&#39;

答案 8 :(得分:-1)

正如我在DatePicker插件给出的可选参数中看到的那样,插件没有onHover函数。

但是,如果您有生成DatePicker的代码副本,您实际上可以在插件中添加自己的.hover()jquery方法,以便在鼠标进入元素/插件时触发。

以下是.hover()方法的文档。

http://api.jquery.com/hover/