Blog 存档

用样式美化button(2)

时间:2009年03月25日作者:愚人码头查看次数:4,561 views评论次数:1

我们经常使用到a,button,input等标签,通过css加背景等方式来实现按钮的效果。但是要做一个通用的样式类,又能保证在各个浏览器下表现一致,还能有很好的扩展性的按纽可不就那么容易了。好了废话少说。进入正题。

首先我们选择a和button两个标签作为通用按纽的外包装器。主要考虑到,在ie6不支持a以外的:hover伪类,使用a就可以对按钮做悬浮状态,这就是为什么选择他们做为最外层的包装器而不是span或者其他的标签。为什么不用input下面会详细说到。

先来认识一下button的类型(type),button,默认的类型。submit,该可以用来提交表单,功能同<input type=”submit” value=”提交” />。reset,可以用来恢复表单默认值。如下

<form action="">
<input type="text" value="I LOVE CHINA" />
<button type="button">type="button",我是一个默认的button,</button>
<button type="submit">type="submit",我可以用来提交表单</button>
<button type="reset">type="reset",我可以来恢复表单默认值</button>
</form>



之前说了,当button的type属性为submit的时候,同样可以对表单进行提交,那为什么要选择button,而不是input。原因有两点。

  1. 表单中,在css中可以通过标签名字来作为选择器,对输入框和按钮进行样式控制,在不支持css2属性选择器的浏览器中,这点非常重要。
  2. 可以在button内甚至可以嵌入div,p这样的标签标签,其扩展性那是相当的好。

但如果想让button在各个浏览器和各种操作系统下表现一致。还是一件比较让人头疼的事情。

在对button清除padding和border之后,ie6,7都会在上内边距产生1个像素的空间,firefox2,3(beta5)则会产生左右内边距3个像素和上内边距1个像素的空白,opera和safari则不会产生多余的内边距填充。请看图。这些差异给我们美化button上填了很多麻烦。

下面通过一个例子来演示一下通用button的制作

 

Html

	<button class="btn btn-style-1" type="submit"><b><b>有兴趣有兴趣</b></b></button>

在这里采用了三层标签的结构,让最内层<b>的背景repeat-x,得到自适应文字宽度。当然也可以两层标签结构的使用滑动门技术实现。但如果要通用的话,那滑动门的背景至少要有800px的宽(考虑到宽屏,文字长等情况)

Images

左边圆角

中间重复背景

右边圆角

在制作的过程中,也许会问,为什么不将三张合成一张背景,其实原因就是上面提到的。每个浏览器下对button标签的默认内间距解释的都不一样。所以只能通过背景垂直居中的方式来解决三张图片对齐的问题。

CSS

	.btn{
display:inline-block;
display:-moz-inline-stack;
*display:inline;
zoom:1;
margin:0;
border:0;
padding:0 5px 0 0;
text-align:center;
font-family:"微软雅黑",YaHei,"黑体";
vertical-align:middle;
font-size:0.8em;
color:#000;
text-decoration:none;
background:url("../img/yn_btn_pink_right.gif") right  no-repeat;
}
button.btn{
cursor:pointer;
width:auto;
*overflow:visible;
border:0 none;
background-color:none;
vertical-align:middle;
}
.btn b{
display:inline-block;
display:-moz-inline-stack;
*display:inline;
zoom:1;
padding:0 0 0 5px;
position:relative;
white-space:nowrap;
font-weight:normal;
height:22px;
line-height:22px;
background:#FFD8D3 url("../img/yn_btn_pink_left.gif") left  no-repeat;
_background-color:#FFF;
}
button.btn b b{
_margin-top:1px;
padding:0px 8px;
height:22px;
line-height:22px;
cursor:pointer;
background:#FFD8D3 url("../img/yn_btn_pink_center.gif") left repeat-x;
_background-color:#FFF;
}

在css中你会发现其中用到了position:relative;是为了解决ie和firefox下点击后下沉错位的问题。但在opera下还是会没解决掉。还请大家多多帮忙。
在这个例子中还可以在button中嵌入icon的来增加它的视觉效果,篇幅有限就不在这里举例子了。

分类:html+css

中英文混排版行高不等问题

时间:2009年03月25日作者:愚人码头查看次数:2,630 views评论次数:0

淘宝采用的是第一种方法!!!!

基本上快被这个问题搞疯了,症状如下


症状描述:在ie下(6或7,8没有试过)当出现中英文混排,都采用默认字体时,并使用 li 列表做float时,会出现如上图的症状,文字排列上下不对齐的情况。影响了布局的美观性,造成上图情况的原因是中英文的文字基线不同,arial字体的下边缘要比宋体(同为12号)低一个象素,上边缘比宋体矮两个象素,而且英文还有i,y这种上下基线不同的情况。所以当中英文混排对齐时,就会出现明显的高度差异,使排版不均。可见放大图。

采用中英文字均使用宋体的方案

可以解决文字排列不对齐的情况,但宋体英文字是衬线字体(Times New Roman即是英文中的衬线字),字型紧凑,细节较多,排列在一起很醒目,但在连续成文时,容易造成辨识困绕,看错行的情况。关于衬线字体的优缺点,请见这篇文章。相比之下,表示英文还是使用无衬线字体更美观大方。

解决方法一 “饺子”童鞋的 发现。

英文采用tahoma字体–宋体,arial及 tahoma字体比较–arial与tahoma的无衬线体比较精致

当中英文混排时,使用tahoma字体的情形

中英混排,纯中文组合的行高都一致了,但a在hover状态下 下划线与中文粘联在一起

缺陷:使用tahoma字体时,在ie6及ie6以下版本,会导致所有中文字体链接的下划线会出现与字体粘连现象。淘宝使用的也是这一解决方案。相信大型项目,不同的人来共同完成一个页面的模块时,在统一的规范下,使字体更规范,减少错位,而采用带有下划线会出现与字体粘连的tahoma字体,是值得的

以下是携同大米童鞋 发现的。

英文采用arial字体,中文使用宋体。可在<a>标签内注明 line-height:1.231,可解决行高不等以及字体与下划线粘连问题。(不知道大范围中英文混排适不适用,有待后续校验。)

分类:html+css

用li实现分页源码示例

时间:2009年03月25日作者:愚人码头查看次数:2,206 views评论次数:0

<!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“>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=gb2312″ />
<title>有序列表分页源码/样式示例</title>
<style type=”text/css”>
.pagination{
 overflow:hidden;
 margin:0;
 padding:10px 10px 6px 10px;
 border-top:1px solid #f60;
 _zoom:1;
}
.pagination *{
 display:inline;
 float:left;
 margin:0;
 padding:0;
 font-size:12px;
}
.pagination i{
 float:none;
 padding-right:1px;
}
.currentPage b{
 float:none;
 color:#f00;
}
.pagination li{
 list-style:none;
 margin:0 5px;
}
.pagination li li{
 position:relative;
 margin:-2px 0 0;
 font-family: Arial, Helvetica, sans-serif
}
.firstPage a,.previousPage a,.nextPage a,.lastPage a{
 overflow:hidden;
 height:0;
 text-indent:-9999em;
 border-top:8px solid #fff;
 border-bottom:8px solid #fff;
}
.pagination li li a{
 margin:0 1px;
 padding:0 4px;
 border:3px double #fff;
 +border-color:#eee;
 background:#eee;
 color:#06f;
 text-decoration:none;
}
.pagination li li a:hover{
 background:#f60;
 border-color:#fff;
 +border-color:#f60;
 color:#fff;
}
li.firstPage{
 margin-left:40px;
 border-left:3px solid #06f;
}
.firstPage a,.previousPage a{
 border-right:12px solid #06f;
}
.firstPage a:hover,.previousPage a:hover{
 border-right-color: #f60;
}
.nextPage a,.lastPage a{
 border-left:12px solid #06f;
}
.nextPage a:hover,.lastPage a:hover{
 border-left-color:#f60;
}
li.lastPage{
 border-right:3px solid #06f;
}
li li.currentState a{
 position:relative;
 margin:-1px 3px;
 padding:1px 4px;
 border:3px double #fff;
 +border-color:#f60;
 background:#f60;
 color:#fff;
}
li.currentState,.currentState a,.currentState a:hover{
 border-color:#fff #ccc;
 cursor:default;
}
</style>
</head>
<body>
<ul class=”pagination” title=”分页列表”>
  <li class=”totalAnnal”>总记录数:<i>3</i></li>
  <li class=”totalPage”>总页数:<i>3</i></li>
  <li class=”currentPage”>当前页:<b>3</b></li>
  <li class=”firstPage currentState”><a href=”javascript:;” title=”首页”>首页</a></li>
  <li class=”previousPage currentState”><a href=”javascript:;” title=”前一页”>前一页</a></li>
  <li>
    <ol>
      <li><a title=”转到第1页” href=”javascript:;”>1</a></li>
      <li><a title=”转到第2页” href=”javascript:;”>2</a></li>
      <li class=”currentState” title=”当前页”><a href=”javascript:;”>3</a></li>
      <li><a title=”转到第4页” href=”javascript:;”>4</a></li>
      <li><a title=”转到第5页” href=”javascript:;”>5</a></li>
      <li><a title=”转到第6页” href=”javascript:;”>6</a></li>
      <li><a title=”转到第7页” href=”javascript:;”>7</a></li>
      <li><a title=”转到第8页” href=”javascript:;”>8</a></li>
      <li><a title=”转到第9页” href=”javascript:;”>9</a></li>
    </ol>
  </li>
  <li class=”nextPage”><a href=”javascript:;” title=”后一页”>后一页</a></li>
  <li class=”lastPage”><a href=”javascript:;” title=”尾页”>尾页</a></i>
</ul>
</body>
</html>

分类:html+css

显示当前状态的导航

时间:2009年03月25日作者:愚人码头查看次数:2,155 views评论次数:0

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN”
        “http://www.w3.org/TR/html4/strict.dtd“>
<html lang=”en”>
<head>
 <meta http-equiv=”content-type” content=”text/html; charset=utf-8″>
 <title>Dynamic Navigation with CSS and Javascript: Example 7</title>
<style type=”text/css”>
body { font-family:verdana; }
#content { float:left; width:400px; border:1px solid #ccc; margin-left:20px; padding:2px 10px 10px 10px; }
ul { margin:0; padding:0; list-style: none; width:200px; float:left; }
ul li { margin:0 0 1px 0; padding:0; }
ul li a {
 display:block;
 padding:8px;
 text-decoration:none;
 background: #eee;
 color: #039;
}
ul li a:hover {
 background: #ffc;
}
ul li a.selected {
 background: #c63;
 color:#fff;
}
#content div { display:none; }
#content div.on { display:block; }
</style>
<script type=”text/javascript”>
function applySelectedTo(link) {
 var ul = document.getElementsByTagName(“ul”)[0]; // get the first ul tag on the page
 var allLinks = ul.getElementsByTagName(“a”); // get all the links within that ul
 for (var i=0; i<allLinks.length; i++) { // iterate through all those links
  allLinks[i].className = “”; // and assign their class names to nothing
 }
 link.className = “selected”;  // finally, assign class=”selected” to our chosen link
 var allDivs = document.getElementsByTagName(“div”);
 for (var k=0; k<allDivs.length; k++) {
  allDivs[k].className = “”;
 }
 var lyricId = link.getAttribute(“href”).split(“#”)[1];
 lyricId = document.getElementById(lyricId);
 lyricId.className = “on”;
}
</script>
</head>
<body>
<h1>A list of links (styled, selected state, onclick, return false, and does something)</h1>
<ul>
 <li><a onclick=”applySelectedTo(this);return false;” href=”#heartbreakHotel”>Heartbreak Hotel</a></li>
 <li><a onclick=”applySelectedTo(this);return false;” href=”#blueSuedeShoes”>Blue Suede Shoes</a></li>
 <li><a onclick=”applySelectedTo(this);return false;” href=”#houndDog” class=”selected”>Hound Dog</a></li>
 <li><a onclick=”applySelectedTo(this);return false;” href=”#dontBeCruel”>Don’t Be Cruel</a></li>
 <li><a onclick=”applySelectedTo(this);return false;” href=”#teddyBear”>Teddy Bear</a></li>
</ul>
<div id=”content”>
 <div id=”heartbreakHotel”>
  <h2>Heartbreak Hotel</h2>
  <p>Well, since my baby left me,<br />
  I found a new place to dwell.<br />
  Its down at the end of lonely street<br />
  At heartbreak hotel.</p>
  <p>You make me so lonely baby,<br />
  I get so lonely,<br />
  I get so lonely I could die.</p>
  <p>And although its always crowded,<br />
  You still can find some room.<br />
  Where broken hearted lovers<br />
  Do cry away their gloom.</p>
  <p>You make me so lonely baby,<br />
  I get so lonely,<br />
  I get so lonely I could die.</p>
  <p>Well, the bell hops tears keep flowin,<br />
  And the desk clerks dressed in black.<br />
  Well they been so long on lonely street<br />
  They aint ever gonna look back.</p>
  <p>You make me so lonely baby,<br />
  I get so lonely,<br />
  I get so lonely I could die.</p>
  <p>Hey now, if your baby leaves you,<br />
  And you got a tale to tell.<br />
  Just take a walk down lonely street<br />
  To heartbreak hotel.</p>
 </div>
 <div id=”blueSuedeShoes”>
  <h2>Blue Suede Shoes</h2>
  <p>Well, its one for the money,<br />
  Two for the show,<br />
  Three to get ready,<br />
  Now go, cat, go.</p>
  <p>But dont you step on my blue suede shoes.<br />
  You can do anything but lay off of my blue suede shoes.</p>
  <p>Well, you can knock me down,<br />
  Step in my face,<br />
  Slander my name<br />
  All over the place.</p>
  <p>Do anything that you want to do, but uh-uh,<br />
  Honey, lay off of my shoes<br />
  Dont you step on my blue suede shoes.<br />
  You can do anything but lay off of my blue suede shoes.</p>
  <p>You can burn my house,<br />
  Steal my car,<br />
  Drink my liquor<br />
  From an old fruitjar.</p>
  <p>Do anything that you want to do, but uh-uh,<br />
  Honey, lay off of my shoes<br />
  Dont you step on my blue suede shoes.<br />
  You can do anything but lay off of my blue suede shoes.</p>
 </div>
 <div class=”on” id=”houndDog”>
  <h2>Hound Dog</h2>
  <p>You aint nothin but a hound dog<br />
  Cryin all the time.<br />
  You aint nothin but a hound dog<br />
  Cryin all the time.<br />
  Well, you aint never caught a rabbit<br />
  And you aint no friend of mine.</p>
  <p>When they said you was high classed,<br />
  Well, that was just a lie.<br />
  When they said you was high classed,<br />
  Well, that was just a lie.<br />
  You aint never caught a rabbit<br />
  And you aint no friend of mine.</p>
 </div>
 <div id=”dontBeCruel”>
  <h2>Don’t Be Cruel</h2>
  <p>You know I can be found,<br />
  Sitting home all alone,<br />
  If you cant come around,<br />
  At least please telephone.<br />
  Dont be cruel to a heart thats true.</p>
  <p>Baby, if I made you mad<br />
  For something I might have said,<br />
  Please, lets forget the past,<br />
  The future looks bright ahead,<br />
  Dont be cruel to a heart thats true.<br />
  I dont want no other love,<br />
  Baby its just you Im thinking of.</p>
  <p>Dont stop thinking of me,<br />
  Dont make me feel this way,<br />
  Come on over here and love me,<br />
  You know what I want you to say.<br />
  Dont be cruel to a heart thats true.<br />
  Why should we be apart?<br />
  I really love you baby, cross my heart.</p>
  <p>Lets walk up to the preacher<br />
  And let us say I do,<br />
  Then youll know youll have me,<br />
  And Ill know that Ill have you,<br />
  Dont be cruel to a heart thats true.<br />
  I dont want no other love,<br />
  Baby its just you Im thinking of.</p>
  <p>Dont be cruel to a heart thats true.<br />
  Dont be cruel to a heart thats true.<br />
  I dont want no other love,<br />
  Baby its just you Im thinking of.</p>
 </div>
 <div id=”teddyBear”>
  <h2>Teddy Bear</h2>
  <p>Baby let me be,<br />
  Your lovin teddy bear<br />
  Put a chain around my neck,<br />
  And lead me anywhere<br />
  Oh let me be<br />
  Your teddy bear.</p>
  <p>I dont wanna be a tiger<br />
  Cause tigers play too rough<br />
  I dont wanna be a lion<br />
  cause lions aint the kind<br />
  You love enough.<br />
  Just wanna be, your teddy bear<br />
  Put a chain around my neck<br />
  And lead me anywhere<br />
  Oh let me be<br />
  Your teddy bear.</p>
  <p>Baby let me be, around you every night<br />
  Run your fingers through my hair,<br />
  And cuddle me real tight.</p>
 </div>
</div>
</body>
</html>

分类:html+css

用JS+css美化下拉框(select)

时间:2009年03月25日作者:愚人码头查看次数:3,056 views评论次数:0

一直以来用CSS控制select都没有实现过。

==================================================

<!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“>
<HTML>
<HEAD>
<TITLE>搜索条</TITLE>
<META NAME=”Generator” CONTENT=”EditPlus”>
<META NAME=”Author” CONTENT=”">
<META NAME=”Keywords” CONTENT=”">
<META NAME=”Description” CONTENT=”">
<style>
/*basic*/
*{padding:0;margin:0;color:#000;font:12px/20px Arial,Sans-serif,”宋体”;}
/*elements*/
.clear{clear:both;height:0px;overflow:hidden;}
ul,li,ol{list-style-type:none;list-style-position:outside;}
button,.btnNormal{height:22px;line-height:18px;padding:0 9px!important;padding:0 5px;}
a{color:#0042ff;text-decoration:underline;}
a,a *{cursor:pointer;}
a img{border:0;}
.searchTool{float:left;width:520px;}
.searchTool .searchExtend{float:left;line-height:24px;_padding-top:5px;}
.searchTool .radio{vertical-align:middle;margin-left:10px;margin-right:2px;*margin-right:0;}
.searchTool .txtSearch{float:left;width:232px;padding:2px 2px 0 2px;height:20px;line-height:20px;vertical-align:bottom;border:1px solid #3e99d4;}
.searchTool .selSearch{float:left;width:60px;background:#fff;height:22px;line-height:22px;border:1px solid #3e99d4;border-left:0;}
.searchTool .nowSearch{float:left;width:40px;height:20px;line-height:22px;overflow:hidden;padding-left:4px;}
.searchTool .btnSel{float:right;border-left:1px solid #3e99d4;width:14px;height:22px;}
.searchTool .btnSel a{background:url(http://static.youku.com/v1.0.0217/index/img/btn_sel.gif) no-repeat center center;display:block;width:14px;height:22px;}
.searchTool .btnSel a:hover{background:url(http://static.youku.com/v1.0.0217/index/img/btn_sel_over.gif) no-repeat center center;border:1px solid #fff;width:12px;height:20px;}
.searchTool .selOption{z-index:9999;position:absolute;margin-left:-1px;width:60px;background:#fff;border:1px solid #3e99d4;}
.searchTool .selOption a{display:block;height:21px;padding-left:5px;line-height:21px;color:#000;text-decoration:none;}
.searchTool .selOption a:hover{color:#fff;background:#95d5f1;}
.searchTool .btnSearch{float:left;margin-left:10px;width:58px;height:22px;line-height:22px;border:1px solid #3e99d4;overflow:hidden;}
.searchTool .btnSearch a{background:url(http://static.youku.com/v1.0.0217/index/img/bg_nav_option.gif) repeat-x center -6px;display:block;text-decoration:none;height:22px;line-height:22px;overflow:hidden;}
.searchTool .btnSearch a:hover{background:url(http://static.youku.com/v1.0.0217/index/img/bg_nav_option_over.gif) repeat-x center center;border:1px solid #fff;height:20px;line-height:20px;}
.searchTool .btnSearch .lbl{cursor:pointer;display:block;width:40px;padding-left:5px;letter-spacing:5px;text-align:center;height:18px;padding-top:1px;margin:0 auto;filter:progid:DXImageTransform.Microsoft.DropShadow(color=#daeefa,offX=1,offY=1,positives=true);}
.searchTool .btnSearch a:hover .lbl{padding-top:0px;}
</style>
<script>
function drop_mouseover(pos){
 try{window.clearTimeout(timer);}catch(e){}
}
function drop_mouseout(pos){
 var posSel=document.getElementById(pos+”Sel”).style.display;
 if(posSel==”block”){
  timer = setTimeout(“drop_hide(‘”+pos+”‘)”, 1000);
 }
}
function drop_hide(pos){
 document.getElementById(pos+”Sel”).style.display=”none”;
}
function search_show(pos,searchType,href){
    document.getElementById(pos+”SearchType”).value=searchType;
    document.getElementById(pos+”Sel”).style.display=”none”;
    document.getElementById(pos+”Slected”).innerHTML=href.innerHTML;
    document.getElementById(pos+’q').focus();
    var sE = document.getElementById(“searchExtend”);
    if(sE != undefined && searchType == “bar”){
     sE.style.display=”block”;
    }else if(sE != undefined){
     sE.style.display=”none”;
    }
 try{window.clearTimeout(timer);}catch(e){}
 return false;
}
</script>
</HEAD>
<BODY>
<div class=”searchTool”>
<form method=”get” action=”http://so.youku.com/search_playlist” name=”headSearchForm” id=”headSearchForm” onsubmit=”return dosearch(this);”>
     <input class=”txtSearch” id=”headq” name=”q” type=”text” value=”闯关东” />
     <input name=”searchdomain” type=”hidden” value=”http://so.youku.com“>
     <input id=”headSearchType” name=”searchType” type=”hidden” value=”playlist”>
     <div class=”selSearch”>
    <div class=”nowSearch” id=”headSlected” onclick=”if(document.getElementById(‘headSel’).style.display==’none’){document.getElementById(‘headSel’).style.display=’block’;}else {document.getElementById(‘headSel’).style.display=’none’;};return false;” onmouseout=”drop_mouseout(‘head’);”>专辑</div>
    <div class=”btnSel”><a href=”#” onclick=”if(document.getElementById(‘headSel’).style.display==’none’){document.getElementById(‘headSel’).style.display=’block’;}else {document.getElementById(‘headSel’).style.display=’none’;};return false;” onmouseout=”drop_mouseout(‘head’);”></a></div>
    <div class=”clear”></div>
    <ul class=”selOption” id=”headSel” style=”display:none;”>
     <li><a href=”#” onclick=”return search_show(‘head’,'video’,this)” onmouseover=”drop_mouseover(‘head’);” onmouseout=”drop_mouseout(‘head’);”>视频</a></li>
     <li><a href=”#” onclick=”return search_show(‘head’,'playlist’,this)” onmouseover=”drop_mouseover(‘head’);” onmouseout=”drop_mouseout(‘head’);”>专辑</a></li>
     <li><a href=”#” onclick=”return search_show(‘head’,'user’,this)” onmouseover=”drop_mouseover(‘head’);” onmouseout=”drop_mouseout(‘head’);”>会员</a></li>
     <li><a href=”#” onclick=”return search_show(‘head’,'bar’,this)” onmouseover=”drop_mouseover(‘head’);” onmouseout=”drop_mouseout(‘head’);”>看吧</a></li>
     <li><a href=”#” onclick=”return search_show(‘head’,'pk’,this)” onmouseover=”drop_mouseover(‘head’);” onmouseout=”drop_mouseout(‘head’);”>PK擂台</a></li>
    </ul>
     </div>
     <div class=”btnSearch”>
    <a href=”#” onclick=”javascript:return dosearch(document.getElementById(‘headSearchForm’));”><span class=”lbl”>搜索</span></a>
     </div>
          <div class=”searchExtend” id=”searchExtend” name=”searchExtend” style=”display:none”>
           <input type=”radio” class=”radio” name=”sbt” value=”post” onclick=”csbt(this,this.form.sbts);” />搜贴子<input type=”radio” name=”sbt” value=”user” onclick=”csbt(this,this.form.sbts);” class=”radio” />按作者搜<input type=”hidden” name=”sbts” value=”bar”>
     </div>
          <div class=”clear”></div>
     </form>
   </div>
   <div class=”clear”></div>
  </div>
 </div>
</BODY>
</HTML>

分类:JS

分享:Javascript字串处理

时间:2009年03月25日作者:愚人码头查看次数:2,117 views评论次数:0

//剪去字串两头空格
function trim(str)
{
    return str.replace(/^ */,”).replace(/ *$/,”);
}

//是否整数
function isInteger(str)
{
    var str = trim(str);
    if (!str.search(/^[0-9]+$/)) return true;
    else return false;
}

//是否浮点数
function isFloat(str)
{
    var str = trim(str);
    if (!str.search(/^[0-9]+\.[0-9]+$/)) return true;
    else return false;
}

分类:JS

在FF解决自动保存input框内容,通过回车选中

时间:2009年03月25日作者:愚人码头查看次数:2,435 views评论次数:0

在FF中如果在input框中抓了回车键后,ie的自动保存,无法通过回车键完成。

可以通过下列的方法实现,原理,延长页面回车后的动作。

function key_submit(evt)
{
 if(evt==null) evt=window.event;
 if(evt.keyCode==13) {//捕捉回车键
  tempUserName=document.getElementById(”loginForm”).fldEmail.value;
  window.setTimeout(’preloginSubmit()’,100);//延迟100毫秒触发
 }
}
function preloginSubmit()
{
 if (tempUserName==document.getElementById(”loginForm”).fldEmail.value)
  loginSubmit();
 else
  return;
}

分类:JS

共享一份Javascript 编程规范

时间:2009年03月25日作者:愚人码头查看次数:2,047 views评论次数:0

前言

相当不错的 Javascript 编程风格规范,建议大家采用此规范编写 Javascript。原文链接: http://dojotoolkit.org/developer/StyleGuide

翻译(Translated by):feelinglucky{at}gmail.com,转载请注明出处、作者和翻译者,谢谢配合。

本文地址: http://code.google.com/p/grace/wiki/DojoStyle

Any violation to this guide is allowed if it enhances readability.

所有的代码都要变成可供他人容易阅读的。

快读参考

核心 API 请使用下面的风格:

结构 规则 注释
模块 小写 不要使用多重语义(Never multiple words)
骆驼  
公有方法 混合 其他的外部调用也可以使用 lower_case(),这样的风格
公有变量 混合  
常量 骆驼 或 大写  

下面的虽然不是必要的,但建议使用:

结构 规则
私有方法 混合,例子:_mixedCase
私有变量 混合,例子:_mixedCase
方法(method)参数 混合,例子:_mixedCase, mixedCase
本地(local)变量 混合,例子:_mixedCase, mixedCase

命名规范

  1. 变量名称 必须为 小写字母。
  2. 类的命名使用骆驼命名规则,例如:
    Account, EventHandler
  3. 常量 必须 在对象(类)或者枚举变量的前部声明。枚举变量的命名必须要有实际的意义,并且其成员 必须 使用骆驼命名规则或使用大写:
    var NodeTypes = {
        Element : 1,
        DOCUMENT: 2
        }
  4. 简写单词 不能使用 大写名称作为变量名:
    getInnerHtml(), getXml(), XmlDocument
  5. 方法的命令 必须 为动词或者是动词短语:
    obj.getSomeValue()
  6. 公有类的命名 必须 使用混合名称(mixedCase)命名。
  7. CSS 变量的命名 必须 使用其对应的相同的公共类变量。
  8. 私有类的变量属性成员 必须 使用混合名称(mixedCase)命名,并前面下下划线(_)。例如:
    var MyClass = function(){
        var _buffer;
        this.doSomething = function(){
        };
        }
  9. 变量如果设置为私有,则前面 必须 添加下划线。
    this._somePrivateVariable = statement;
  10. 通用的变量 必须 使用与其名字一致的类型名称:
    setTopic(topic) // 变量 topic 为 Topic 类型的变量
  11. 所有的变量名 必须 使用英文名称。
  12. 变量如有较广的作用域(large scope),必须使用全局变量;此时可以设计成一个类的成员。相对的如作用域较小或为私有变量则使用简洁的单词命名。
  13. 如果变量有其隐含的返回值,则避免使用其相似的方法:
    getHandler(); // 避免使用 getEventHandler()
  14. 公有变量必须清楚的表达其自身的属性,避免字义含糊不清,例如:
    MouseEventHandler,而非 MseEvtHdlr。

    请再次注意这条规定,这样做得的好处是非常明显的。它能明确的表达表达式所定义的含义。例如:

    dojo.events.mouse.Handler // 而非 dojo.events.mouse.MouseEventHandler
  15. 类/构造函数 可以使用 扩展其基类的名称命名,这样可以正确、迅速的找到其基类的名称:
    EventHandler
        UIEventHandler
        MouseEventHandler

    基类可以在明确描述其属性的前提下,缩减其命名:

    MouseEventHandler as opposed to MouseUIEventHandler.

特殊命名规范

  1. 术语 “get/set” 不要和一个字段相连,除非它被定义为私有变量。
  2. 前面加 “is” 的变量名 应该 为布尔值,同理可以为 “has”, “can” 或者 “should”。
  3. 术语 “compute” 作为变量名应为已经计算完成的变量。
  4. 术语 “find” 作为变量名应为已经查找完成的变量。
  5. 术语 “initialize” 或者 “init” 作为变量名应为已经实例化(初始化)完成的类或者其他类型的变量。
  6. UI (用户界面)控制变量应在名称后加控制类型,例如: leftComboBox, TopScrollPane。
  7. 复数必须有其公共的名称约定(原文:Plural form MUST be used to name collections)。
  8. 带有 “num” 或者 “count” 开头的变量名约定为数字(对象)。
  9. 重复变量建议使用 “i”, “j”, “k” (依次类推)等名称的变量。
  10. 补充用语必须使用补充词,例如: get/set, add/remove, create/destroy, start/stop, insert/delete, begin/end, etc.
  11. 能缩写的名称尽量使用缩写。
  12. 避免产生歧义的布尔变量名称,例如:
    isNotError, isNotFound 为非法
  13. 错误类建议在变量名称后加上 “Exception” 或者 “Error”。
  14. 方法如果返回一个类,则应该在名称上说明返回什么;如果是一个过程,则应该说明做了什么。

文件

  1. 缩进请使用 4 个空白符的制表位。
  2. 如果您的编辑器支持 文件标签_(file tags),请加添如下的一行使我们的代码更容易阅读:
    // vim:ts=4:noet:tw=0:

    译注:老外用 VIM 编辑器比较多,此条可以选择遵循。  

    1. 代码折叠必须看起来是完成并且是合乎逻辑的: 
      var someExpression = Expression1
              + Expression2
              + Expression3;
              var o = someObject.get(
              Expression1,
              Expression2,
              Expression3
              );

      注:表达式的缩进与变量声明应为一致的。

注:函数的参数应采用明确的缩进,缩进规则与其他块保持一致。

变量

  1. 变量必须在声明初始化以后才能使用,即便是 NULL 类型。
  2. 变量不能产生歧义。
  3. 相关的变量集应该放在同一代码块中,非相关的变量集不应该放在同一代码块中。
  4. 变量应该尽量保持最小的生存周期。
  5. 循环/重复变量的规范:
    1. 只有循环控制块的话,则必须使用 FOR 循环。
    2. 循环变量应该在循环开始前就被初始化;如使用 FOR 循环,则使用 FOR 语句初始化循环变量。
    3. “do … while” 语句是被允许的。
    4. “break” 和 “continue” 语句仍然允许使用(但请注意)。
  6. 条件表达式
    1. 应该尽量避免复杂的条件表达式,如有必要可以使用临时布尔变量。
    2. The nominal case SHOULD be put in the “if” part and the exception in the “else” part of an “if” statement.
    3. 应避免在条件表达式中加入块。
  7. 杂项
    1. 尽量避免幻数(Magic numbers),他们应该使用常量来代替。
    2. 浮点变量必须指明小数点后一位(即使是 0)。
    3. 浮点变量必须指明实部,即使它们为零(使用 0. 开头)。

布局

  1. 普通代码段 应该 看起来如下:
    while (!isDone){
        doSomething();
        isDone = moreToDo();
        }
  2. IF 语句 应该 看起来像这样:
    if (someCondition){
        statements;
        } else if (someOtherCondition){
        statements;
        } else {
        statements;
        }
  3. FOR 语句 应该 看起来像这样:
    for (initialization; condition; update){
        statements;
        }
  4. WHILE 语句 应该 看起来像这样:
    while (!isDone) {
        doSomething();
        isDone = moreToDo();
        }
  5. DO … WHILE 语句 应该 看起来像这样:
    do {
        statements;
        } while (condition);
  6. SWITCH 语句 应该 看起来像这样:
    switch (condition) {
        case ABC:
        statements;
        //  fallthrough
        case DEF:
        statements;
        break;
        default:
        statements;
        break;
        }
  7. TRY … CATCH 语句 应该 看起来像这样:
    try {
        statements;
        } catch(ex) {
        statements;
        } finally {
        statements;
        }
  8. 单行的 IF – ELSE,WHILE 或者 FOR 语句也 必须 加入括号,不过他们可以这样写:
    if (condition){ statement; }
        while (condition){ statement; }
        for (intialization; condition; update){ statement; }

空白

  1. 操作符 建议 使用空格隔开(包括三元操作符)。
  2. 下面的关键字 避免使用 空白隔开:
    • break
    • catch
    • continue
    • do
    • else
    • finally
    • for
    • function (如果为匿名函数,例如:var foo = function(){}; )
    • if
    • return
    • switch
    • this
    • try
    • void
    • while
    • with
  3. 下面的关键字必须使用空白隔开:
    • case
    • default
    • delete
    • function (如果为申明,例如:function foo(){}; )
    • in
    • instanceof
    • new
    • throw
    • typeof
    • var
  4. 逗号(,) 建议 使用空白隔开。
  5. 冒号(:) 建议 使用空白隔开。
  6. 点(.) 在后部 建议 使用空白隔开。
  7. 点(.) 避免 在前部使用空白。
  8. 函数调用和方法 避免 使用空白,例如: doSomething(someParameter); // 而非 doSomething (someParameter)
  9. 逻辑块 之间使用空行。
  10. 声明 建议 对齐使其更容易阅读。

注释

  1. 生涩的代码就 没有必要 添加注释了,首先您需要 重写 它们。
  2. 所有的注释请使用英文。
  3. 从已解决的方案到未开发的功能,注释 必须 与代码相关。
  4. 大量的变量申明后 必须 跟随一段注释。
  5. 注释需要说明的是代码段的用处,尤其是接下来的代码段。
  6. 注释 没有必要 每行都添加。

 

文档

下面提供了一些基本的函数或者对象的描述方法:

  • 总结(summary): 简短的表述此函数或者对象实现的目的
  • 描述(description): 对于此函数或者类的简短的描述
  • 返回(return): 描述此函数返回什么(并不包括返回类型)

基本函数信息

function(){
// summary: Soon we will have enough treasure to rule all of New Jersey.
// description: or we could just get a new roomate.
//		Look, you go find him.  He don't yell at you.
//		All I ever try to do is make him smile and sing around
//		him and dance around him and he just lays into me.
//		He told me to get in the freezer 'cause there was a carnival in there.
// returns:  Look, a Bananarama tape!
}

对象函数信息

没有返回值描述

{
// summary: Dingle, engage the rainbow machine!
// description:
//		Tell you what, I wish I was--oh my g--that beam,
//		coming up like that, the speed, you might wanna adjust that.
//		It really did a number on my back, there. I mean, and I don't
//		wanna say whiplash, just yet, cause that's a little too far,
//		but, you're insured, right?
}

函数的声明

在有的情况下,对于函数的调用和声明是隐义(invisible)的。在这种情况下,我们没有办法在函数中加入说明等(供程序调用)。如果您遭遇了这种情况,您可以使用一个类来封装函数。

注:此此方法只能在函数没有初始化的参数情况下。如过不是,则它们会被忽略。

dojo.declare(
"foo",
null,
{
// summary: Phew, this sure is relaxing, Frylock.
// description:
//		Thousands of years ago, before the dawn of
//		man as we knew him, there was Sir Santa of Claus: an
//		ape-like creature making crude and pointless toys out
//		of dino-bones, hurling them at chimp-like creatures with
//		crinkled hands regardless of how they behaved the
//		previous year.
// returns: Unless Carl pays tribute to the Elfin Elders in space.
}
);

参数

  1. 简单类型

    简单的类型的参数可以直接在函数参数定义中注释说明。

    function(/*String*/ foo, /*int*/ bar)...
  2. 可变类型参数

    下面是几个修饰符供参考:

    • ? 可选参数
    • 说面参数范围不确定
    • [] 数组
      function(/*String?*/ foo, /*int...*/ bar, /*String[]*/ baz)...
  3. 全局参数描述

    如果你想增加一个描述,你可以将它们移至初始化块。

基本信息格式为: *关键字* 描述字段 *key* Descriptive sentence

参数和变量的格式为: *关键字* ~*类型*~ 描述字段 *key* ~*type*~ Descriptive sentence

注: *关键字* 和 ~*类型*~ 可以使用任何字母和数字表述。

function (foo, bar) {
// foo: String
//		used for being the first parameter
// bar: int
//		used for being the second parameter
}

变量

由于实例变量、原型变量和外部变量的声明是一致的,所以有很多的方法声明、修改变量。具体的如何定义和定位应在变量最先出现的位置指明变量的名称、类型、作用域等信息。

function foo() {
// myString: String
// times: int
//		How many times to print myString
// separator: String
//		What to print out in between myString*
this.myString = "placeholder text";
this.times = 5;
}
foo.prototype.setString = function (myString) {
this.myString = myString;
}
foo.prototype.toString = function() {
for(int i = 0; i < this.times; i++) {
dojo.debug(this.myString);
dojo.debug(foo.separator);
}
}
foo.separator = "=====";

对象中的变量注释

应使用和对象值和方法一致的标注方式,比如在他们声明的时候:

{
// key: String
//		A simple value
key: "value",
// key2: String
//		Another simple value
}

返回值

因为函数可以同时返回多个不同(类型)的值,所以应每个返回值之后加入返回类型的注释。注释在行内注释即可,如果所有的返回值为同一类型,则指明返回的类型;如为多个不同的返回值,则标注返回类型为”mixed”。

function() {
if (arguments.length) {
return "You passed argument(s)"; // String
} else {
return false; // Boolean
}
}

伪代码(有待讨论)

有时候您需要在函数或者类中添加对于此函数和类的功能性流程描述。如果您打算这样做,您可以使用 /*======== (= 字符最好出现 5 次或者更多),这样做的好处就是可以不用将这些东西加入代码(译注:原作者的意思可能为代码管理系统)。

这样看起来在 /*===== =====*/ 会有非常长的一段注释,等待功能调整完毕以后就可以考虑是否删除。

/*=====
module.pseudo.kwArgs = {
// url: String
//		The location of the file
url: "",
// mimeType: String
//		text/html, text/xml, etc
mimeType: ""
}
=====*/
function(/*module.pseudo.kwArgs*/ kwArgs){
dojo.debug(kwArgs.url);
dojo.debug(kwArgs.mimeType);
}
分类:JS

图片和文字布局问题

时间:2009年03月25日作者:愚人码头查看次数:2,783 views评论次数:0

这两天制作页面遇如下图的问题, 整理了一下方便自己同时也希望方便了同行们…
备注: 根据要求,XHTML架构是固定以下的代码, 另外图片跟文字的,宽度比例是随内容而改变

实现左文右图板块-Gulu77

这问题一时三刻没有弄出来,通过在经典论坛中得到了wiseinfo帮助,给了一些提示在此非常感激!

解决方案:

左图右文板块http://blog.gulu77.com/demo/200804/imgfloatleft.html

左文右图板块http://blog.gulu77.com/demo/200804/imgfloatright.html

针对IE的http://blog.gulu77.com/demo/200804/floattest.html

问题解决思路:
IE系列浏览器-
在.block内的div设置浮动后问题得以解决。(据我个人理解,IE的解析为 给同等级元素设置float后,自动赋予对象,所谓的100%高度空间!所以内容才会分为左右两块)

非IE浏览器-
在非IE中则没有float 100%高度空间的解析, 而我采用了wiseinfo所说的用display:table-call;把.block内的div作为表格单元格显示问题得以解决

延伸思考:
为什么在IE中同等级元素设置float后,会占100%高度空间,这样的解析在非IE中确没有,到底谁的解析才是正确? 他们的解析机制是什么?

注意文中所指的IE为:  IE5.5 / IE6 / IE7

分类:html+css

下拉框(select)遮住弹出层问题

时间:2009年03月25日作者:愚人码头查看次数:4,984 views评论次数:0

在IE6下下拉框(select)会遮住弹出层,用样式办法暂时无法解决,包括z-index这个属性。

想了一个最变态的方法:

就是在层弹出的时候把下拉框给隐藏掉,用display:none属性或visable:hiddle属性;当层隐藏的时候再把下拉框给显示出来:

function hiddenselect()
{
    var f = document.forms["form1"];
    if (f)
    {
    for (i=0;i<f.elements.length;i++)
   {
   if (f.elements[i].type==”select-one”)
   {
   f.elements[i].style.display=”none”;
   }
   }
   }
}

function showselect()
{
    var f = document.forms["form1"];
    if (f)
    {
    for (i=0;i<f.elements.length;i++)
   {
   if (f.elements[i].type==”select-one”)
   {
   f.elements[i].style.display=”";
   }
   }
   }
}

分类:html+css, JS