最近项目需要做一个简单的可编辑表格,网上有人提供了一个思路,点击表格就插入input;
基于这个思路进行了jquery的实现:
核心js:
/**
* 编辑事件
*/
UFFC.pages.BudgetPage.prototype.initedittable = function () {
$('td').click(function () {//如果上一个输入框消失的慢的话 可以加一个延时
if ($('#tempinput').attr('id') == undefined) {
$(this).html('<input id="tempinput" type="text" value="' + $(this).text() + '" ' +
'οnblur="UFFC.pages.BudgetPage.tdOnblur(this);" size=10/>');
//焦点
$('#tempinput').focusEnd();
}
});
};
/**
* td输入框消失事件
*/
UFFC.pages.BudgetPage.tdOnblur = function (th) {
var $this = $(th).parent();
var value = $('#tempinput').val();
$('#tempinput').remove();
$($this).html(value);
};
/**
* 焦点定位到末尾 来自前辈
*/
$.fn.focusEnd = function () {
this.setCursorPosition(this.val().length);
}
//焦点定位到最末尾
$.fn.setCursorPosition = function (position) {
if (this.length == 0) return this;
return $(this).setSelection(position, position);
}
//焦点定位到最末尾
$.fn.setSelection = function (selectionStart, selectionEnd) {
if (this.length == 0) return this;
var input = this[0];
if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
} else if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(selectionStart, selectionEnd);
}
return this;
}
思路很简单,代码也很简单~
<div class="bodytable">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<th> 部门</th>
<th> 项目</th>
<th> 预算</th>
<th> 余额</th>
<th> 审批人</th>
</tr>
<tr>
<td>财务1</td>
<td>微1</td>
<td>1000001</td>
<td>10001</td>
<td>91</td>
</tr>
<tr>
<td>服务2</td>
<td>微2</td>
<td>1000002</td>
<td>10002</td>
<td>2</td>
</tr>
<tr>
<td>务3</td>
<td>微</td>
<td>1000003</td>
<td>10003</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>微4</td>
<td>1000004</td>
<td>10004</td>
<td>4</td>
</tr>
</table>
</div>
css:
table {
border: 0px;
cellpadding: 0px;
cellspacing: 0px;
border-bottom: #c0c4c3 solid 1px;
}
tr th {
width: 250px;
height: 40px;
font: inherit;
}
table tr td {
border-top: #c0c4c3 solid 1px;
width: 110px;
text-align: center;
line-height: 24px;
height: 40px;
}
最终效果:
没有严禁的测试,如果有问题,大家随时交流~