从日历中获取想要的日期(一)

2014-11-23 23:22:33 · 作者: · 浏览: 0
要想实现这个效果,首先得有一个日历,刚好之前有写过一个简单的日历插件,所以就派上用场了。下面是日历的代码:
复制代码
html>
<script>
var Calendar = function (id) {
this.init(id);
};
Calendar.prototype = {
constructor: Calendar,
init: function (id) {
this.nowDate = new Date();
this.year = this.nowDate.getFullYear();
this.month = this.nowDate.getMonth();
this.date = this.nowDate.getDate();
this.day = this.nowDate.getDay();
this.createElement(id);
},
isLeapYear: function (year) {
return (year > 0) && !(year % 4) && ((year % 100) || !(year % 400));
},
getDate: function () {
var date = this.nowDate;
return date.getFullYear() + "年" + date.getMonth() + 1 + "月" + date.getDate() + "日";
},
createElement: function (id) {
var cal = document.getElementById(id);
var div = document.createElement("div");
div.innerHTML = this.getDate();
cal.appendChild(div);
var tab = document.createElement("table");
cal.appendChild(tab);
this.thead = document.createElement("thead");
this.tbody = document.createElement("tbody");
this.tr = document.createElement("tr");
this.td = document.createElement("td");
tab.appendChild(this.thead);
tab.appendChild(this.tbody);
this.tHead();
this.tBody(this.year);
},
tHead: function () {
var weekDays = ["日", "一", "二", "三", "四", "五", "六"];
var tr = this.tr.cloneNode(true);
this.thead.appendChild(tr);
weekDays.forEach(function (item) {
var td = this.td.cloneNode(true);
td.innerHTML = item;
tr.appendChild(td);
},this)
},
tBody: function (year) {
var monthNum = [31, this.isLeapYear(year) 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][this.month];
var date = new Date(this.year, this.month, 1);
var tr = this.tr.cloneNode(true);
this.tbody.appendChild(tr);
var td;
for (var i = 0; i < date.getDay(); i ++) {
td = this.td.cloneNode(true);
td.innerHTML = "";
tr.appendChild(td);
}
for (var j = 1; j <= monthNum; j++) {
if ((i + j) % 7 === 1) {
tr = this.tr.cloneNode(true);
this.tbody.appendChild(tr);
}
td = this.td.cloneNode(true);
tr.appendChild(td);
td.innerHTML = j;
td.style.background = "green";
td.style.color = "black";
td.style.textAlign = "center";
if (j === this.date) {
td.style.color = "red";
}
}
}
};
var calendar = new Calendar("calendar");
复制代码
  现在有了这个日历,我们要做的就是当点击输入框的时候怎样把日历显示在下方,这就涉及到偏移量的问题了,就是求出输入框相对于页面可见区域的的位置。
  求出输入框的横向偏移量代码:
复制代码
getElementLeft: function (target) {
var actualLeft = target.offsetLeft;
var current = target.offsetParent;
while (current !== null){
actualLeft += current.offse