鸟食轩

 Microsoft .NET[C#] MVP 2003
随笔 - 429, 文章 - 235, 评论 - 5527, 引用 - 356
数据加载中……

自动适应输入内容宽度的TextBox控件

    在ASP.NET的上面,TextBox是表单设计时最常用的控件之一。很多时候为了页面的紧凑和美观,我们需要适当的限制TextBox的显示宽度,但是如果TextBox过于窄了之后,又会给用户的填写带了不便,而且更麻烦的是很多时候我们并不知道用户到底会往那个TextBox里填多少内容。为了解决这些问题,下面给大家推荐一个可自动适应输入内容的宽度的TextBox控件。

    本控件是从TextBox控件继承,设计原理是使用一个agent input(type=text)来做为实际的用户录入的TextBox,在焦点切换的过程中完成background input和agent input的属性同步。 

    下面的代码完成两个input之间的样式和属性同步:

function ATB_SwitchToInputAgent(input) 
    注意:不能使用style=style或for( attribute in style)的方式来赋值,否这引起onpropertychange的死循环递归

    第二个问题是使用onpropertychange属性来同步agent input的宽度和其内容宽度相等,代码如下: 
function ATB_AutoIncreaseWidth(input) 

    
if ( input.style.display == 'none' ) return
    
var spanWrapper = input.parentElement; 
    
var userInput = spanWrapper.firstChild; 
    userInput.value 
= input.value; 
    
var absOffsetWidth = GetAbsoluteOffsetLeft(input); 
    
var docClientWidth = window.document.body.clientWidth; 
    
if ( input.scrollWidth < userInput.clientWidth ) 
    { 
        
if ( absOffsetWidth + styleWidth >= docClientWidth )  
        { 
            input.style.width 
= docClientWidth - absOffsetWidth; 
        } 
        
else 
        { 
            input.style.width 
= userInput.clientWidth+2
        } 
        
return
    } 
    
var styleWidth = parseInt(input.style.width); 
    
if ( styleWidth != input.scrollWidth+2 ) 
    { 
        
if ( absOffsetWidth + styleWidth >= docClientWidth )  
        { 
            input.style.width 
= docClientWidth - absOffsetWidth; 
        } 
        
else 
        { 
            input.style.width 
= input.scrollWidth+2
        } 
    } 
    这里需要注意的是当增长的agent input的最右端超出了IE的body区域时,需要停止其增长,否则用户看不见输入的东西了。 

    演示效果如下:
    
*

附 AdjustableTextBox 控件源码

posted on 2004-12-24 00:17 birdshome 阅读(7634) 评论(11)  编辑 收藏 所属分类: Asp.net控件开发

评论

#1楼   回复  引用  查看    

不错啊!
2004-12-24 08:55 | BillChen      

#2楼   回复  引用  查看    

使用你的源码实验一下,发现有错误,提示"Stack overflow at line:0"
2004-12-24 11:24 | BillChen      

#3楼[楼主]   回复  引用  查看    

你用的什么浏览器?我在IE6sp1下没有任何问题呀。
还有一点,这个控件要放在Table里比较好,否则Agent Input的定位有一点点小问题:(
2004-12-26 01:23 | birdshome      

#4楼   回复  引用  查看    

不错!
2004-12-28 07:27 | 吕震宇      

#5楼   回复  引用  查看    

怎么用,我用不来啊!
2005-03-09 11:49 | shidier      

#6楼   回复  引用    

在。net中怎么让他呈现为一条线阿

#7楼[楼主]   回复  引用  查看    

一条线?like this:
2005-07-12 01:38 | birdshome      

#8楼   回复  引用    

怎样在TextBox里只能输入数字不能输入字符啊
2006-03-14 12:49 | huwk[未注册用户]

#9楼   回复  引用    

那就用验证表达式呗!!"/d/d",应该是这么写的吧!
2007-07-21 09:42 | nanhaizizd[未注册用户]

#10楼   回复  引用    

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

不支持这个,
提示"Stack overflow at line:0" 错误。
2007-10-21 19:53 | test_error[未注册用户]

#11楼   回复  引用    

输入的内容“→”



发表评论

昵称: [登录] [注册]

主页:

邮箱:(仅博主可见)

评论内容:

  登录  注册

[使用Ctrl+Enter键快速提交评论]

0 81217


相关文章:

相关链接: