用icon 開啟 bootstrap-daterangepicker
最近有個專案要用到DateRangepicker,在網路上找到了一個元件:Date Range Picker for Bootstrap.
原始檔與文件說明連結:https://github.com/dangrossman/bootstrap-daterangepicker
範例連結: http://www.dangrossman.info/2012/08/20/a-date-range-picker-for-twitter-bootstrap/
在作者的範例中,預設用法與畫面如下:
<div class="controls">
<div class="input-prepend input-group">
<span class="add-on input-group-addon"><i class="glyphicon glyphicon-calendar fa fa-calendar"></i></span>
<input type="text" style="width: 200px" name="reservation" id="reservation" class="form-control" value="03/18/2013 - 03/23/2013" />
</div>
</div>
</div>
$(document).ready(function() {
$('#reservation').daterangepicker();
});
</script>
嗯...到這邊一切都很美好,在文件說明中,也有說明如何自訂日期顯示格式。
但Demo給同事看了之後,他們問了一個問題:「為什麼點文字欄位旁邊的日期icon不會動?」
在範例討論串中有人提出跟我一樣的問題,有位仁兄回覆說,只要在icon的click event加上$('#reservation').focus()即可。
我試了...但沒有反應!甚麼都沒出現!
開了firebug來看原始碼變化,發現觸發$('#reservation').focus()時,此日期元件區塊的 display:none; 怎麼都不會變成 display: block;
抱著不解決不能下班的決心,狠下心打開此元件的js原始碼來找找看....一路看下去~
原來作者有寫一段功能去偵測當點選Textbox或日期元件以外的區域時,就會隱藏日期元件(outsideClick)。
知道原因後,一切就好解決了:
首先,在頁面上偵測icon是否被點選,當被點選時,就把右邊的textbox兄弟設定focus()。
(若icon跟範例不同要放在textbox右邊,jQuery 尋覽順序顛倒即可)
$(document).ready(function() {
$('#reservation').daterangepicker().prev().on('click',function(){
$(this).next().focus();
});
});
</script>
接著,開啟daterangepicker.js,大約是line: 508,改一下outsideClick方法:
var target = $(e.target);
// if the page is clicked anywhere except within the daterangerpicker/button
// itself then call this.hide()
if (
target.closest(this.element).length ||
target.closest(this.element.next()).length ||
target.closest(this.element.prev()).length ||
target.closest(this.container).length ||
target.closest('.calendar-date').length
) return;
this.hide();
}
Done. 收工.