javascript jQuery Datepicker - 在悬停时获取日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23772962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:32:17  来源:igfitidea点击:

jQuery Datepicker - Get date on hover

javascriptjquerydatepickerhover

提问by eozzy

I'm using thisjQuery datepicker and I'm trying to get the value of the date on hover. I see the plugin has a parameter:

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

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

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

Since the documentation is very limited, I wonder if there're are other options besides click and if not, how can I use eventNameto get the value on hover.

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

采纳答案by pete

The eventNameoption is only used to bind the internal showmethod to an event:

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

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

You could, in theory, use hoverto show the datepicker but you'd have to specify 'mouseenter mouseleave'for the eventNameoption as hoveris a jQuery shortcut method to bind to 'mouseenter mouseleave'.

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

Since you've stated (in comments) that you want the behavior found at kayak.co.in, you can mimic this merely by chaining a mouseenterhandler after the .DatePickercall (no change needed to anything else):

由于您已经声明(在评论中)您希望在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
    }
});

Working demo: http://jsfiddle.net/QgXNn/5/

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

回答by Dave Alperovich

Try this approach:

试试这个方法:

Create a Div for your hover target

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

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

On ready, initialize and bind to hover event to open

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

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

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

});

Fiddle(couldnt reference your picker so i used JQuery UI)

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



Update: Check out the new Fiddle

更新:查看新的Fiddle

I applied my approach to your Fiddle. Now YOUR DatePicker appears when you hover over "Hover Me" and disappears whencursor leaves. I added:

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

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

});

-

——

BTW, I made the DatePicker Dialog disappear on non-hover just for effect. That can easily be changed by removed the adjoining

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

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

回答by Onur Y?ld?r?m

See the editedworking fiddle here, forked from yours.

这里查看编辑过的工作小提琴,从你的那里分叉出来。

// 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);
}

回答by SSS

For your question. I guess you dont want the datepicker to shown on hover but want the values or dates to be shown in the input box on hover. If you want the datepicker to be shown on hover try to use 'mouseover' for eventName Attribute of the plugin Like this

对于你的问题。我猜您不希望日期选择器在悬停时显示,但希望值或日期在悬停时显示在输入框中。如果您希望在悬停时显示日期选择器,请尝试使用“鼠标悬停”作为插件的 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'});

Its not taking the jquery events of hover.

它没有采用悬停的 jquery 事件。

Now for showing the new date in the input tag when the datepicker elements are hovered. You may need to tweak the plugin itself try to find this line 734. The code is

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

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

Change it to

将其更改为

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

As you can see I have used the old mouseover event and not the jquery 'Hover' keyword. If this works you can also try to add a new options parameter in the plugin say 'callon:click' and set this option when you call and pass it to this line 734.

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

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

Using this you can set your own events to call for updating the value of the text box. It would surely work for a single date picker. Please try it and comment on this. But you may have to manipulate more to set the date on click as well.

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

回答by mfirdaus

Since the plugin already has bound the changefunctions on a click, we can use that by attaching an event for hoverand simply triggering that. So something like:

由于插件已经change在 a上绑定了函数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

例子

回答by Irvin Dominin

You can use delegation on hover the dates elments, if so force a click on the element itself.

您可以在将日期元素悬停时使用委托,如果是这样,请强制单击元素本身。

Code:

代码:

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

Since I can't let the plugin works on newer versions of jQuery I have to use delegate

因为我不能让插件在较新版本的 jQuery 上工作,所以我必须使用 delegate

Demo: http://jsfiddle.net/IrvinDominin/fFc7h/

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

回答by Rohit

Use eventName 'mouseover' instead of 'hover'

使用 eventName 'mouseover' 而不是 'hover'

回答by ReNiSh A R

By using jQuery and jQuery UI:

通过使用 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>

check demo @: http://jsfiddle.net/renishar/ZVf48/4/

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

include jQuery and jQuery UI libraries also..

还包括 jQuery 和 jQuery UI 库。

回答by heyitsmarcucu

As what I have seen in the optional parameters given by the DatePicker plugin, there's no onHover function for the plugin.

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

However, if you have a copy of the code that generates the DatePicker, you could actually add your own .hover() method of jquery in the plugin to trigger when the mouse enters the element / plugin.

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

Here is the documentation for the .hover() method.

这是 .hover() 方法的文档。

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

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