Wednesday, May 13, 2009

jQuery Sample

Sample 1.
Collapse

html code:

<!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" xml:lang="en" lang="en">
  <head>
<title>JQuery Collapse</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="Common.js"></script>
<link type="text/css" rel="stylesheet" href="styleCss.css"></link>
</head>
<body>
<a href="#" id="mostrar">MOSTRAR</a>
<div id="caja">
<p>Lorem ipsum dolor sit amet,...</p>
</div>
</body>
</html>

CSS code:

body {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 11px;
color: #666666; 
}
a{color:#993300; text-decoration:none;}
#caja {
width:70%;
display: none;
padding:5px;
border:2px solid #FADDA9;
background-color:#FDF4E1;
}
#mostrar{
display:block;
width:70%;
padding:5px;
border:2px solid #D0E8F4;
background-color:#ECF8FD;
}

jQuery code:

$(document).ready(function() {
$(function(){

$("#mostrar").click(function(event) {
event.preventDefault();
$("#caja").slideToggle();
});

$("#caja a").click(function(event) {
event.preventDefault();
$("#caja").slideUp();
});
}
);

});

Sunday, May 10, 2009

上传图片汇总

1.最简单的单文件上传(没花头)

效果图:

说明:这是最基本的文件上传,在asp.net1.x中没有这个FileUpload控件,只有html的上传控件,那时候要把html控件转化为服务器控件,很不好用。其实所有文件上传的美丽效果都是从这个FileUpload控件衍生,第一个例子虽然简单却是根本。

后台代码:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void bt_upload_Click(object sender, EventArgs e)
    {
        try
        {
            if (FileUpload1.PostedFile.FileName == "")
            {
                this.lb_info.Text = "请选择文件!";
            }
            else
            {
                string filepath = FileUpload1.PostedFile.FileName;
                string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);
                string serverpath = Server.MapPath("images/") + filename;
                FileUpload1.PostedFile.SaveAs(serverpath);
                this.lb_info.Text = "上传成功!";
            }
        }
        catch (Exception ex)
        {
            this.lb_info.Text = "上传发生错误!原因是:" + ex.ToString();
        }
    }
}

前台代码:
 <table style="width: 343px">
            <tr>
                <td style="width: 100px">
                    单文件上传</td>
                <td style="width: 100px">
                </td>
            </tr>
            <tr>
                <td style="width: 100px">
                    <asp:FileUpload ID="FileUpload1" runat="server" Width="475px" />
                    </td>
                <td style="width: 100px">
                    <asp:Button ID="bt_upload" runat="server" OnClick="bt_upload_Click" Text="上传" /></td>
            </tr>
            <tr>
                <td style="width: 100px; height: 21px;">
                    <asp:Label ID="lb_info" runat="server" ForeColor="Red" Width="183px"></asp:Label></td>
                <td style="width: 100px; height: 21px">
                </td>
            </tr>
        </table>

2.多文件上传

效果图:


后台代码:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void bt_upload_Click(object sender, EventArgs e)
    {
        
            if ((FileUpload1.PostedFile.FileName == "" && FileUpload2.PostedFile.FileName == "")&&FileUpload3.PostedFile.FileName == "")
            {
                this.lb_info.Text = "请选择文件!";
            }
            else
            {
                HttpFileCollection myfiles = Request.Files;
                for (int i = 0; i < myfiles.Count; i++)
                {
                    HttpPostedFile mypost = myfiles[i];
                    try
                    {
                        if (mypost.ContentLength > 0)
                        {
                             string filepath = mypost.FileName;
                             string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);
                             string serverpath = Server.MapPath("images/") + filename;
                             mypost.SaveAs(serverpath);
                             this.lb_info.Text = "上传成功!";
                        }
                    }
                    catch (Exception error)
                    {
                        this.lb_info.Text = "上传发生错误!原因:" + error.ToString();
                    }

                }
               
            }
        }
       
    }

前台代码:
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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 runat="server">
    <title>多文件上传 清清月儿http://blog.csdn.net/21aspnet/</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table style="width: 343px">
            <tr>
                <td style="width: 100px">
                    多文件上传</td>
                <td style="width: 100px">
                </td>
            </tr>
            <tr>
                <td style="width: 100px">
                    <asp:FileUpload ID="FileUpload1" runat="server" Width="475px" />
                    </td>
                <td style="width: 100px">
                    </td>
            </tr>
            <tr>
                <td style="width: 100px">
                    <asp:FileUpload ID="FileUpload2" runat="server" Width="475px" /></td>
                <td style="width: 100px">
                </td>
            </tr>
            <tr>
                <td style="width: 100px">
                    <asp:FileUpload ID="FileUpload3" runat="server" Width="475px" /></td>
                <td style="width: 100px">
                </td>
            </tr>
            <tr>
                <td style="width: 100px">
                    <asp:Button ID="bt_upload" runat="server" OnClick="bt_upload_Click" Text="一起上传" />
                    <asp:Label ID="lb_info" runat="server" ForeColor="Red" Width="183px"></asp:Label></td>
                <td style="width: 100px">
                </td>
            </tr>
        </table>
    
    </div>
    </form>
</body>
</html>

3.客户端检查上传文件类型(以上传图片为例)

效果图:

后台代码和1.最简单的单文件上传一样;
前台代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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 runat="server">
    <title>清清月儿 http://blog.csdn.net/21aspnet</title>
<script   language="javascript">  
 function Check_FileType()
{
var str=document.getElementById("FileUpload1").value;
 var pos = str.lastIndexOf(".");
 var lastname = str.substring(pos,str.length)  
 if (lastname.toLowerCase()!=".jpg" && lastname.toLowerCase()!=".gif")
 {
     alert("您上传的文件类型为"+lastname+",图片必须为.jpg,.gif类型");
     return false;
 }
 else 
 {
  return true;
 }
 </script> 

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table style="width: 343px">
            <tr>
                <td style="width: 104px">
                    文件上传判断</td>
                <td style="width: 100px">
                </td>
            </tr>
            <tr>
                <td style="width: 104px">
                    <asp:FileUpload ID="FileUpload1" runat="server" Width="400px" />
                    </td>
                <td style="width: 100px">
                    <asp:Button ID="bt_upload" runat="server" OnClick="bt_upload_Click" Text="上传"  OnClientClick="return Check_FileType()"/></td>
            </tr>
            <tr>
                <td style="width: 104px; height: 21px;">
                    <asp:Label ID="lb_info" runat="server" ForeColor="Red" Width="183px"></asp:Label></td>
                <td style="width: 100px; height: 21px">
                </td>
            </tr>
        </table>
    
    </div>
    </form>
</body>
</html>
说明:点击上传时先触发客户端事件Check_FileType;

4.服务器端检查上传文件类型(以上传图片为例)

效果图:


后台代码:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void bt_upload_Click(object sender, EventArgs e)
    {
        try
        {
            if (FileUpload1.PostedFile.FileName == "")
            {
                this.lb_info.Text = "请选择文件!";
            }
            else
            {
                string filepath = FileUpload1.PostedFile.FileName;
                if (IsAllowedExtension(FileUpload1) == true)
                {

                    string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);
                    string serverpath = Server.MapPath("images/") + filename;
                    FileUpload1.PostedFile.SaveAs(serverpath);
                    this.lb_info.Text = "上传成功!";
                }
                else 
                {
                    this.lb_info.Text = "请上传图片";
                }
            }
        }
        catch (Exception error)
        {
            this.lb_info.Text = "上传发生错误!原因:" + error.ToString();
        }
    }
   public static bool IsAllowedExtension(FileUpload hifile)
    {
        string strOldFilePath = "", strExtension = "";
        string[] arrExtension =   { ".gif", ".jpg", ".jpeg", ".bmp", ".png" };
        if (hifile.PostedFile.FileName != string.Empty)
        {
            strOldFilePath = hifile.PostedFile.FileName;
            strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));
            for (int i = 0; i < arrExtension.Length; i++)
            {
                if (strExtension.Equals(arrExtension[i]))
                {
                    return true;
                }
            }
        }
        return false;
    }  

}

 5.服务器端检查上传文件类型(可以检测真正文件名) 
其实方法4并不好,因为用户可以把XXX.txt伪装为XXX.jpg。

效果图:


后台代码:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    //清清月儿 http://blog.csdn.net/21aspnet
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void bt_upload_Click(object sender, EventArgs e)
    {
        try
        {
            if (FileUpload1.PostedFile.FileName == "")
            {
                this.lb_info.Text = "请选择文件!";
            }
            else
            {
                string filepath = FileUpload1.PostedFile.FileName;
                if (IsAllowedExtension(FileUpload1) == true)
                {
                    string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);
                    string serverpath = Server.MapPath("images/") + filename;
                    FileUpload1.PostedFile.SaveAs(serverpath);
                    this.lb_info.Text = "上传成功!";
                }
                else 
                {
                    this.lb_info.Text = "请上传图片";
                }
            }
        }
        catch (Exception error)
        {
            this.lb_info.Text = "上传发生错误!原因:" + error.ToString();
        }
    }
    public static bool IsAllowedExtension(FileUpload hifile)
    {
        System.IO.FileStream fs = new System.IO.FileStream(hifile.PostedFile.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
        System.IO.BinaryReader r = new System.IO.BinaryReader(fs);
        string fileclass = "";
        byte buffer;
        try
        {
            buffer = r.ReadByte();
            fileclass = buffer.ToString();
            buffer = r.ReadByte();
            fileclass += buffer.ToString();

        }
        catch 
        {
           
        }
        r.Close();
        fs.Close();
        if (fileclass == "255216" || fileclass == "7173")//说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
        {
            return true;
        }
        else 
        {
            return false;
        }

    }  

}

6.上传文件文件名唯一性处理(时间戳+SessionID)

效果图:


说明:年月日时分秒+临时session+原文件名 如果大家怕还会重复可以加GUID
后台代码:

try
        {
            if (FileUpload1.PostedFile.FileName == "")
            {
                this.lb_info.Text = "请选择文件!";
            }
            else
            {
                string filepath = FileUpload1.PostedFile.FileName;
                string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);
                string serverpath = Server.MapPath("images/") + System.DateTime.Now.ToString("yyy-MM-dd-hh-mm-ss") + Session.SessionID + filename;
                FileUpload1.PostedFile.SaveAs(serverpath);
                this.lb_info.Text = "上传成功!";
            }
        }
        catch (Exception error)
        {
            this.lb_info.Text = "上传发生错误!原因:" + error.ToString();
        }

注:GUID的方法:Guid myGuid=Guid.NewGuid();

7.上传图片生成等比例缩略图

效果图:


缩略图代码:
ImageThumbnail.cs
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

public class ImageThumbnail
{
    public Image ResourceImage;
    private int ImageWidth;
    private int ImageHeight;
    public string ErrorMessage;

    public ImageThumbnail(string ImageFileName)
    {
        ResourceImage = Image.FromFile(ImageFileName);
        ErrorMessage = "";
    }

    public bool ThumbnailCallback()
    {
        return false;
    }


    // 方法1,按大小
    public bool ReducedImage(int Width, int Height, string targetFilePath)
    {
        try
        {
            Image ReducedImage;
            Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);
            ReducedImage = ResourceImage.GetThumbnailImage(Width, Height, callb, IntPtr.Zero);
            ReducedImage.Save(@targetFilePath, ImageFormat.Jpeg);
            ReducedImage.Dispose();
            return true;
        }
        catch (Exception e)
        {
            ErrorMessage = e.Message;
            return false;
        }
    }


    // 方法2,按百分比  缩小60% Percent为0.6 targetFilePath为目标路径
    public bool ReducedImage(double Percent, string targetFilePath)
    {
        try
        {
            Image ReducedImage;
            Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);
            ImageWidth = Convert.ToInt32(ResourceImage.Width * Percent);
            ImageHeight = (ResourceImage.Height)*ImageWidth/ ResourceImage.Width;//等比例缩放
            ReducedImage = ResourceImage.GetThumbnailImage(ImageWidth, ImageHeight, callb, IntPtr.Zero);
            ReducedImage.Save(@targetFilePath, ImageFormat.Jpeg);
            ReducedImage.Dispose();
            return true;
        }
        catch (Exception e)
        {
            ErrorMessage = e.Message;
            return false;
        }
    }


}

后台代码:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void bt_upload_Click(object sender, EventArgs e)
    {
        try
        {
            if (FileUpload1.PostedFile.FileName == "")
            {
                this.lb_info.Text = "请选择文件!";
            }
            else
            {
                string filepath = FileUpload1.PostedFile.FileName;
                string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);
                string serverpath1 = Server.MapPath("images/") + filename;
                string serverpath2 = Server.MapPath("images/") + System.DateTime.Now.ToString("yyy-MM-dd-hh-mm-ss") + Session.SessionID + filename;
                FileUpload1.PostedFile.SaveAs(serverpath1);
                ImageThumbnail img = new ImageThumbnail(filepath);
                img.ReducedImage(0.4, serverpath2);//0.4表示缩小40%
                this.lb_info.Text = "上传成功!";
            }
        }
        catch (Exception error)
        {
            this.lb_info.Text = "上传发生错误!原因:" + error.ToString();
        }
    }


}

8.上传图片加水印(文字水印,图片水印,文字+图片水印)

效果图:

原图

水印

给图片加水印以后(注意右上角+正下方)


代码:
DrawImg.cs  出自http://www.codeproject.com/csharp/watermark.asp
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
public class DrawImg
{
 private string  WorkingDirectory = string.Empty ; //路径
 private string  ImageName = string.Empty;   //被处理的图片
 private string  ImageWater = string.Empty;  //水印图片
 private string  FontString = string.Empty;  //水印文字
 

 enum DealType{NONE,WaterImage,WaterFont,DoubleDo}; //枚举命令

 private DealType dealtype;
 

 public DrawImg()
 {}

 public string PublicWorkingDirectory
 {
  get
  {
   return WorkingDirectory;
  }
  set
  {
   WorkingDirectory = value;
  }
 }

 public string PublicImageName
 {
  get
  {
   return ImageName;
  }
  set
  {
   ImageName = value;
  }
 }


 public string PublicImageWater 
 {
  get
  {
   return ImageWater;
  }
  set  //设置了水印图片的话说明是要水印图片效果的
  {
   dealtype = DealType.WaterImage;
   ImageWater = value;
  }
 }

 public string PublicFontString
 {
  get
  {
   return FontString;
  }
  set //设置了水印文字的话说明是要水印文字效果的
  {
   dealtype = DealType.WaterFont;
   FontString = value;
  }
 }

 

 public void DealImage()
 {
  IsDouble();

  switch( dealtype )
  {
   case DealType.WaterFont: WriteFont(); break;
   case DealType.WaterImage: WriteImg(); break;
   case DealType.DoubleDo: WriteFontAndImg(); break;
  }

 }

 private void IsDouble()
 {
  if(ImageWater+""!="" && FontString+""!="")
  {
            dealtype = DealType.DoubleDo;
  }
 }

 private void WriteFont()
 {
  //set a working directory
  //string WorkingDirectory = @"C:\Watermark_src\WaterPic";

  //define a string of text to use as the Copyright message
  //string Copyright = "Copyright ?2002 - AP Photo/David Zalubowski";

  //create a image object containing the photograph to watermark
  Image imgPhoto = Image.FromFile(WorkingDirectory + ImageName);
  int phWidth = imgPhoto.Width;
  int phHeight = imgPhoto.Height;

  //create a Bitmap the Size of the original photograph
  Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);

  bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

  //load the Bitmap into a Graphics object 
  Graphics grPhoto = Graphics.FromImage(bmPhoto);

  //------------------------------------------------------------
  //Step #1 - Insert Copyright message
  //------------------------------------------------------------

  //Set the rendering quality for this Graphics object
  grPhoto.SmoothingMode = SmoothingMode.AntiAlias;

  //Draws the photo Image object at original size to the graphics object.
  grPhoto.DrawImage(
   imgPhoto,                               // Photo Image object
   new Rectangle(0, 0, phWidth, phHeight), // Rectangle structure
   0,                                      // x-coordinate of the portion of the source image to draw. 
   0,                                      // y-coordinate of the portion of the source image to draw. 
   phWidth,                                // Width of the portion of the source image to draw. 
   phHeight,                               // Height of the portion of the source image to draw. 
   GraphicsUnit.Pixel);                    // Units of measure

  //-------------------------------------------------------
  //to maximize the size of the Copyright message we will 
  //test multiple Font sizes to determine the largest posible 
  //font we can use for the width of the Photograph
  //define an array of point sizes you would like to consider as possiblities
  //-------------------------------------------------------
  int[] sizes = new int[]{16,14,12,10,8,6,4};

  Font crFont = null;
  SizeF crSize = new SizeF();

  //Loop through the defined sizes checking the length of the Copyright string
  //If its length in pixles is less then the image width choose this Font size.
  for (int i=0 ;i<7; i++)
  {
   //set a Font object to Arial (i)pt, Bold
   //crFont = new Font("arial", sizes[i], FontStyle.Bold);

   crFont = new Font("arial",sizes[i],FontStyle.Bold);

   //Measure the Copyright string in this Font
   crSize = grPhoto.MeasureString(FontString, crFont);

   if((ushort)crSize.Width < (ushort)phWidth)
    break;
  }

  //Since all photographs will have varying heights, determine a 
  //position 5% from the bottom of the image
  int yPixlesFromBottom = (int)(phHeight *.05);

  //Now that we have a point size use the Copyrights string height 
  //to determine a y-coordinate to draw the string of the photograph
  float yPosFromBottom = ((phHeight - yPixlesFromBottom)-(crSize.Height/2));

  //Determine its x-coordinate by calculating the center of the width of the image
  float xCenterOfImg = (phWidth/2);

  //Define the text layout by setting the text alignment to centered
  StringFormat StrFormat = new StringFormat();
  StrFormat.Alignment = StringAlignment.Center;

  //define a Brush which is semi trasparent black (Alpha set to 153)
  SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(153, 0, 0, 0));

  //Draw the Copyright string
  grPhoto.DrawString(FontString,                 //string of text
   crFont,                                   //font
   semiTransBrush2,                           //Brush
   new PointF(xCenterOfImg+1,yPosFromBottom+1),  //Position
   StrFormat);

  //define a Brush which is semi trasparent white (Alpha set to 153)
  SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(153, 255, 255, 255));

  //Draw the Copyright string a second time to create a shadow effect
  //Make sure to move this text 1 pixel to the right and down 1 pixel
  grPhoto.DrawString(FontString,                 //string of text
   crFont,                                   //font
   semiTransBrush,                           //Brush
   new PointF(xCenterOfImg,yPosFromBottom),  //Position
   StrFormat);    
  
  imgPhoto = bmPhoto;
  grPhoto.Dispose();

  //save new image to file system.
  imgPhoto.Save(WorkingDirectory + ImageName + "_finally.jpg", ImageFormat.Jpeg);
  imgPhoto.Dispose();
  
  //Text alignment
 }


 private void WriteImg()
 {
  //set a working directory
  //string WorkingDirectory = @"C:\Watermark_src\WaterPic";

  //create a image object containing the photograph to watermark
  Image imgPhoto = Image.FromFile(WorkingDirectory + ImageName);
  int phWidth = imgPhoto.Width;
  int phHeight = imgPhoto.Height;

  //create a Bitmap the Size of the original photograph
  Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);

  bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

  //load the Bitmap into a Graphics object 
  Graphics grPhoto = Graphics.FromImage(bmPhoto);

  //create a image object containing the watermark
  Image imgWatermark = new Bitmap(WorkingDirectory + ImageWater);
  int wmWidth = imgWatermark.Width;
  int wmHeight = imgWatermark.Height;

  //Set the rendering quality for this Graphics object
  grPhoto.SmoothingMode = SmoothingMode.AntiAlias;

  //Draws the photo Image object at original size to the graphics object.
  grPhoto.DrawImage(
   imgPhoto,                               // Photo Image object
   new Rectangle(0, 0, phWidth, phHeight), // Rectangle structure
   0,                                      // x-coordinate of the portion of the source image to draw. 
   0,                                      // y-coordinate of the portion of the source image to draw. 
   phWidth,                                // Width of the portion of the source image to draw. 
   phHeight,                               // Height of the portion of the source image to draw. 
   GraphicsUnit.Pixel);                    // Units of measure


  //------------------------------------------------------------
  //Step #2 - Insert Watermark image
  //------------------------------------------------------------

  //Create a Bitmap based on the previously modified photograph Bitmap
  Bitmap bmWatermark = new Bitmap(bmPhoto);
  bmWatermark.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
  //Load this Bitmap into a new Graphic Object
  Graphics grWatermark = Graphics.FromImage(bmWatermark);

  //To achieve a transulcent watermark we will apply (2) color 
  //manipulations by defineing a ImageAttributes object and 
  //seting (2) of its properties.
  ImageAttributes imageAttributes = new ImageAttributes();

  //The first step in manipulating the watermark image is to replace 
  //the background color with one that is trasparent (Alpha=0, R=0, G=0, B=0)
  //to do this we will use a Colormap and use this to define a RemapTable
  ColorMap colorMap = new ColorMap();

  //My watermark was defined with a background of 100% Green this will
  //be the color we search for and replace with transparency
  colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
  colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);

  ColorMap[] remapTable = {colorMap};

  imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

  //The second color manipulation is used to change the opacity of the 
  //watermark.  This is done by applying a 5x5 matrix that contains the 
  //coordinates for the RGBA space.  By setting the 3rd row and 3rd column 
  //to 0.3f we achive a level of opacity
  float[][] colorMatrixElements = { 
           new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},       
           new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},        
           new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},        
           new float[] {0.0f,  0.0f,  0.0f,  0.3f, 0.0f},        
           new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}}; 
  ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);

  imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default,
   ColorAdjustType.Bitmap);

  //For this example we will place the watermark in the upper right
  //hand corner of the photograph. offset down 10 pixels and to the 
  //left 10 pixles

  int xPosOfWm = ((phWidth - wmWidth)-10);
  int yPosOfWm = 10;

  grWatermark.DrawImage(imgWatermark, 
   new Rectangle(xPosOfWm,yPosOfWm,wmWidth,wmHeight),  //Set the detination Position
   0,                  // x-coordinate of the portion of the source image to draw. 
   0,                  // y-coordinate of the portion of the source image to draw. 
   wmWidth,            // Watermark Width
   wmHeight,      // Watermark Height
   GraphicsUnit.Pixel, // Unit of measurment
   imageAttributes);   //ImageAttributes Object

  //Replace the original photgraphs bitmap with the new Bitmap
  imgPhoto = bmWatermark;
  grPhoto.Dispose();
  grWatermark.Dispose();

  //save new image to file system.
  imgPhoto.Save(WorkingDirectory + ImageName +"_finally.jpg", ImageFormat.Jpeg);
  imgPhoto.Dispose();
  imgWatermark.Dispose();

 }


 private void WriteFontAndImg()
 {  
  
  //create a image object containing the photograph to watermark
  Image imgPhoto = Image.FromFile(WorkingDirectory + ImageName);
  int phWidth = imgPhoto.Width;
  int phHeight = imgPhoto.Height;

  //create a Bitmap the Size of the original photograph
  Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);

  bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

  //load the Bitmap into a Graphics object 
  Graphics grPhoto = Graphics.FromImage(bmPhoto);

  //create a image object containing the watermark
  Image imgWatermark = new Bitmap(WorkingDirectory + ImageWater);
  int wmWidth = imgWatermark.Width;
  int wmHeight = imgWatermark.Height;

  //------------------------------------------------------------
  //Step #1 - Insert Copyright message
  //------------------------------------------------------------

  //Set the rendering quality for this Graphics object
  grPhoto.SmoothingMode = SmoothingMode.AntiAlias;

  //Draws the photo Image object at original size to the graphics object.
  grPhoto.DrawImage(
   imgPhoto,                               // Photo Image object
   new Rectangle(0, 0, phWidth, phHeight), // Rectangle structure
   0,                                      // x-coordinate of the portion of the source image to draw. 
   0,                                      // y-coordinate of the portion of the source image to draw. 
   phWidth,                                // Width of the portion of the source image to draw. 
   phHeight,                               // Height of the portion of the source image to draw. 
   GraphicsUnit.Pixel);                    // Units of measure

  //-------------------------------------------------------
  //to maximize the size of the Copyright message we will 
  //test multiple Font sizes to determine the largest posible 
  //font we can use for the width of the Photograph
  //define an array of point sizes you would like to consider as possiblities
  //-------------------------------------------------------
  int[] sizes = new int[]{16,14,12,10,8,6,4};//这里可以修改文字

  Font crFont = null;
  SizeF crSize = new SizeF();

  //Loop through the defined sizes checking the length of the Copyright string
  //If its length in pixles is less then the image width choose this Font size.
  for (int i=0 ;i<7; i++)
  {
   //set a Font object to Arial (i)pt, Bold
   crFont = new Font("arial", sizes[i], FontStyle.Bold);
   //Measure the Copyright string in this Font
   crSize = grPhoto.MeasureString(FontString, crFont);

   if((ushort)crSize.Width < (ushort)phWidth)
    break;
  }

  //Since all photographs will have varying heights, determine a 
  //position 5% from the bottom of the image
  int yPixlesFromBottom = (int)(phHeight *.05);

  //Now that we have a point size use the Copyrights string height 
  //to determine a y-coordinate to draw the string of the photograph
  float yPosFromBottom = ((phHeight - yPixlesFromBottom)-(crSize.Height/2));

  //Determine its x-coordinate by calculating the center of the width of the image
  float xCenterOfImg = (phWidth/2);

  //Define the text layout by setting the text alignment to centered
  StringFormat StrFormat = new StringFormat();
  StrFormat.Alignment = StringAlignment.Center;

  //define a Brush which is semi trasparent black (Alpha set to 153)
  SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(153, 0, 0, 0));

  //Draw the Copyright string
  grPhoto.DrawString(FontString,                 //string of text
   crFont,                                   //font
   semiTransBrush2,                           //Brush
   new PointF(xCenterOfImg+1,yPosFromBottom+1),  //Position
   StrFormat);

  //define a Brush which is semi trasparent white (Alpha set to 153)
  SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(153, 255, 255, 255));

  //Draw the Copyright string a second time to create a shadow effect
  //Make sure to move this text 1 pixel to the right and down 1 pixel
  grPhoto.DrawString(FontString,                 //string of text
   crFont,                                   //font
   semiTransBrush,                           //Brush
   new PointF(xCenterOfImg,yPosFromBottom),  //Position
   StrFormat);                               //Text alignment

   

  //------------------------------------------------------------
  //Step #2 - Insert Watermark image
  //------------------------------------------------------------

  //Create a Bitmap based on the previously modified photograph Bitmap
  Bitmap bmWatermark = new Bitmap(bmPhoto);
  bmWatermark.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
  //Load this Bitmap into a new Graphic Object
  Graphics grWatermark = Graphics.FromImage(bmWatermark);

  //To achieve a transulcent watermark we will apply (2) color 
  //manipulations by defineing a ImageAttributes object and 
  //seting (2) of its properties.
  ImageAttributes imageAttributes = new ImageAttributes();

  //The first step in manipulating the watermark image is to replace 
  //the background color with one that is trasparent (Alpha=0, R=0, G=0, B=0)
  //to do this we will use a Colormap and use this to define a RemapTable
  ColorMap colorMap = new ColorMap();

  //My watermark was defined with a background of 100% Green this will
  //be the color we search for and replace with transparency
  colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
  colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);

  ColorMap[] remapTable = {colorMap};

  imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

  //The second color manipulation is used to change the opacity of the 
  //watermark.  This is done by applying a 5x5 matrix that contains the 
  //coordinates for the RGBA space.  By setting the 3rd row and 3rd column 
  //to 0.3f we achive a level of opacity
  float[][] colorMatrixElements = { 
           new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},       
           new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},        
           new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},        
           new float[] {0.0f,  0.0f,  0.0f,  0.3f, 0.0f},        
           new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}}; 
  ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);

  imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default,
   ColorAdjustType.Bitmap);

  //For this example we will place the watermark in the upper right
  //hand corner of the photograph. offset down 10 pixels and to the 
  //left 10 pixles

  int xPosOfWm = ((phWidth - wmWidth)-10);
  int yPosOfWm = 10;

  grWatermark.DrawImage(imgWatermark, 
   new Rectangle(xPosOfWm,yPosOfWm,wmWidth,wmHeight),  //Set the detination Position
   0,                  // x-coordinate of the portion of the source image to draw. 
   0,                  // y-coordinate of the portion of the source image to draw. 
   wmWidth,            // Watermark Width
   wmHeight,      // Watermark Height
   GraphicsUnit.Pixel, // Unit of measurment
   imageAttributes);   //ImageAttributes Object

  //Replace the original photgraphs bitmap with the new Bitmap
  imgPhoto = bmWatermark;
  grPhoto.Dispose();
  grWatermark.Dispose();

  //save new image to file system.
  imgPhoto.Save(WorkingDirectory + ImageName +"_finally.jpg", ImageFormat.Jpeg);
  imgPhoto.Dispose();
  imgWatermark.Dispose();

        
 }
}


 //水印图片加水印文字
//   ReDrawImg img = new ReDrawImg();
//   img .PublicWorkingDirectory = @"C:\Watermark_src\WaterPic\";
//   img .PublicImageName = "watermark_photo.jpg";
//   img .PublicImageWater = "watermark.bmp";
//   img .PublicFontString = "清清月儿";
//   img .DealImage(); 
  
   //水印文字
   ReDrawImg img = new ReDrawImg();
   img .PublicWorkingDirectory = @"C:\Watermark_src\WaterPic\";
   img .PublicImageName = "watermark_photo.jpg";   
   img .PublicFontString = @"清清月儿";
   img .DealImage();
 

   //水印图片
//   ReDrawImg img = new ReDrawImg();
//   img .PublicWorkingDirectory = @"C:\Watermark_src\WaterPic\";
//   img .PublicImageName = "watermark_photo.jpg";
//   img .PublicImageWater = "watermark.bmp";   
//   img .DealImage(); 
  
 
后台代码:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void bt_upload_Click(object sender, EventArgs e)
    {
        try
        {
            if (FileUpload1.PostedFile.FileName == "")
            {
                this.lb_info.Text = "请选择文件!";
            }
            else
            {
                string filepath = FileUpload1.PostedFile.FileName;
                string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);
                HttpPostedFile UpFile = FileUpload1.PostedFile;//获取上传图片对象
                int filelength = UpFile.ContentLength;//获取上传图片的大小(字节大小)
                   if (CheckBytes(filelength)==true)
                      {
               // string serverpath1 = Server.MapPath("images/") + filename;
                string serverpath2 = Server.MapPath("images/") + System.DateTime.Now.ToString("yyy-MM-dd-hh-mm-ss") + Session.SessionID + filename;
           string newname = System.DateTime.Now.ToString("yyy-MM-dd-hh-mm-ss") + Session.SessionID + filename;//上传到指定文件夹后的图片的新名称                FileUpload1.PostedFile.SaveAs(serverpath2);
                //ImageThumbnail img = new ImageThumbnail(filepath);
                //img.ReducedImage(0.4, serverpath2);
                DrawImg img = new DrawImg();
                img.PublicWorkingDirectory = Server.MapPath("images/");
               // img.PublicImageName = filename;//作者的例子是上传图片已经存在要上传到的文件夹里
                img.PublicImageName =newname;//自己要上传的文件一般不会存在要上传到的文件夹里。这里获取上传成功后的图片文件名称。
                img.PublicFontString = "http://blog.csdn.net/21aspnet";
                img.PublicImageWater = "yyy.jpg";
                img.DealImage();
                this.lb_info.Text = "上传成功!";
                GC.Collect();//释放进程,否则删不掉图片文件
                File.Delete(serverpath);
                }
                 else
                   {
                      this.lb_info.Text = "图片大小不能大于2M!";
                   }
            }
        }
        catch (Exception error)
        {
            this.lb_info.Text = "上传发生错误!原因:" + error.ToString();
        }
    }

    public bool CheckBytes(int FileLength)//限制图片大小
    {
        bool Result = true;
        int Length = 2097152;//2M
        if (FileLength > Length)
        {
            Result = false;
        }
        return Result;
    }
}

Thursday, May 7, 2009

CSS特效

Keep Moving...

CSS文件:
hoverbox.css
*
{
border: 0;
margin: 0;
padding: 0;
}

/* =Basic HTML, Non-essential
----------------------------------------------------------------------*/

a
{
text-decoration: none;
}

body
{
background: #fff;
color: #777;
margin: 0 auto;
padding: 50px;
position: relative;
width: 620px;
}

h1
{
background: inherit;
border-bottom: 1px dashed #ccc;
color: #933;
font: 17px Georgia, serif;
margin: 0 0 10px;
padding: 0 0 5px;
text-align: center;
}

p
{
clear: both;
font: 10px Verdana, sans-serif;
padding: 10px 0;
text-align: center;
}

p a
{
background: inherit;
color: #777;
}

p a:hover
{
background: inherit;
color: #000;
}

/* =Hoverbox Code
----------------------------------------------------------------------*/

.hoverbox
{
cursor: default;
list-style: none;
}

.hoverbox a
{
cursor: default;
}

.hoverbox a .preview
{
display: none;
}

.hoverbox a:hover .preview
{
display: block;
position: absolute;
top: -33px;
left: -45px;
z-index: 1;
}

.hoverbox img
{
background: #fff;
border-color: #aaa #ccc #ddd #bbb;
border-style: solid;
border-width: 1px;
color: inherit;
padding: 2px;
vertical-align: top;
width: 100px;
height: 75px;
}

.hoverbox li
{
background: #eee;
border-color: #ddd #bbb #aaa #ccc;
border-style: solid;
border-width: 1px;
color: inherit;
display: inline;
float: left;
margin: 3px;
padding: 5px;
position: relative;
}

.hoverbox .preview
{
border-color: #000;
width: 200px;
height: 150px;
}

*****************************
ie_fixes.css

/* =Internet Explorer Fixes
----------------------------------------------------------------------*/

.hoverbox a
{
position: relative;
}

.hoverbox a:hover
{
display: block;
font-size: 100%;
z-index: 1;
}

.hoverbox a:hover .preview
{
top: -38px;
left: -50px;
}

.hoverbox li
{
position: static;
}

*************************
html code:
index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Hoverbox Image Gallery</title>
<link rel="stylesheet" href='css/hoverbox.css' type="text/css" media="screen, projection" />
<!--[if lte IE 7]>
<link rel="stylesheet" href='css/ie_fixes.css' type="text/css" media="screen, projection" />
<![endif]-->
</head>
<body>
<marquee><font>Hoverbox Image Gallery</font></marquee>
<ul class="hoverbox">
<li>
<a href="#"><img src="img/photo01.jpg" alt="description" /><img src="img/photo01.jpg" alt="description" class="preview" /></a>
</li>
<li>
<a href="#"><img src="img/photo02.jpg" alt="description" /><img src="img/photo02.jpg" alt="description" class="preview" /></a>
</li>
<li>
<a href="#"><img src="img/photo03.jpg" alt="description" /><img src="img/photo03.jpg" alt="description" class="preview" /></a>
</li>
<li>
<a href="#"><img src="img/photo04.jpg" alt="description" /><img src="img/photo04.jpg" alt="description" class="preview" /></a>
</li>
<li>
<a href="#"><img src="img/photo05.jpg" alt="description" /><img src="img/photo05.jpg" alt="description" class="preview" /></a>
</li>
<li>
<a href="#"><img src="img/photo06.jpg" alt="description" /><img src="img/photo06.jpg" alt="description" class="preview" /></a>
</li>
<li>
<a href="#"><img src="img/photo07.jpg" alt="description" /><img src="img/photo07.jpg" alt="description" class="preview" /></a>
</li>
<li>
<a href="#"><img src="img/photo08.jpg" alt="description" /><img src="img/photo08.jpg" alt="description" class="preview" /></a>
</li>
<li>
<a href="#"><img src="img/photo09.jpg" alt="description" /><img src="img/photo09.jpg" alt="description" class="preview" /></a>
</li>
<li>
<a href="#"><img src="img/photo10.jpg" alt="description" /><img src="img/photo10.jpg" alt="description" class="preview" /></a>
</li>
<li>
<a href="#"><img src="img/photo11.jpg" alt="description" /><img src="img/photo11.jpg" alt="description" class="preview" /></a>
</li>
<li>
<a href="#"><img src="img/photo12.jpg" alt="description" /><img src="img/photo12.jpg" alt="description" class="preview" /></a>
</li>
<li>
<a href="#"><img src="img/photo13.jpg" alt="description" /><img src="img/photo13.jpg" alt="description" class="preview" /></a>
</li>
<li>
<a href="#"><img src="img/photo14.jpg" alt="description" /><img src="img/photo14.jpg" alt="description" class="preview" /></a>
</li>
<li>
<a href="#"><img src="img/photo15.jpg" alt="description" /><img src="img/photo15.jpg" alt="description" class="preview" /></a>
</li>
<li>
<a href="#"><img src="img/photo16.jpg" alt="description" /><img src="img/photo16.jpg" alt="description" class="preview" /></a>
</li>
<li>
<a href="#"><img src="img/photo17.jpg" alt="description" /><img src="img/photo17.jpg" alt="description" class="preview" /></a>
</li>
<li>
<a href="#"><img src="img/photo18.jpg" alt="description" /><img src="img/photo18.jpg" alt="description" class="preview" /></a>
</li>
<li>
<a href="#"><img src="img/photo19.jpg" alt="description" /><img src="img/photo19.jpg" alt="description" class="preview" /></a>
</li>
<li>
<a href="#"><img src="img/photo20.jpg" alt="description" /><img src="img/photo20.jpg" alt="description" class="preview" /></a>
</li>
</ul>
<p id="footer"><a href="http://validator.w3.org/check/referer">XHTML</a> <a href="http://jigsaw.w3.org/css-validator/check/referer">CSS</a> <a href="http://www.contentquality.com/mynewtester/cynthia.exe?Url1=http://host.sonspring.com/hoverbox/">508</a> | Hoverbox by <a href="http://sonspring.com/">Nathan Smith</a>. | Read the <a href="http://sonspring.com/journal/hoverbox-image-gallery">Tutorial</a>.</p>
</body>
</html>

Monday, May 4, 2009

jQuery(八)----Plugins

Keep Moving...

8. Plugins

8.1 Accordion

8.1.1 Accordion(settings)

Make the selected elements Accordion widgets. ? Semantic requirements:

If the structure of your container is flat with unique tags for header and content elements, eg. a definition list 

(dl > dt + dd), you don't have to specify any options at all.

If your structure uses the same elements for header and content or uses some kind of nested structure, you have to 

specify the header elements, eg. via class, see the second example.

Use activate(Number) to change the active content programmatically.

返回值

jQuery

参数

settings (Object): key/value pairs of optional settings.
Hash 选项

active (String|Element|jQuery|Boolean): Selector for the active element, default is the first child, set to false 

to display none at start
header (String|Element|jQuery): Selector for the header element, eg. div.title, a.head, default is the first 

child's tagname
showSpeed (String|Number): Speed for the slideIn, default is 'slow'
hideSpeed (String|Number): Speed for the slideOut, default is 'fast'
selectedClass (String): Class for active header elements, default is 'selected'
示例

说明:

Creates a Accordion from the given definition list

HTML 代码:

<dl id="list1"><dt>Header 1><dd>Content 1</dd>[...]</dl>
jQuery 代码:

$('#list1').Accordion();
说明:

Creates a Accordion from the given div structure

HTML 代码:

<div id="nav"><div><div class="title">Header 1><div>Content 1</div></div>

[...]</div>
jQuery 代码:

$('#list2').Accordion({ header: 'div.title' });
说明:

Creates a Accordion from the given navigation list

HTML 代码:

<ul id="nav"> <li> <a class="head">Header 1> <ul> <li><a href="#">Link 

1</a></li> <li><a href="#">Link 2></a></li> </ul> </li> [...] 

</ul>
jQuery 代码:

$('#nav').Accordion({ header: 'a.head' });
说明:

Updates the #status element with the text of the selected header every time the accordion changes

jQuery 代码:

$('#accordion').Accordion().change(function(event, newHeader, oldHeader, newContent, oldContent) { 

$('#status').html(newHeader.text()); });

8.1.2 activate(index)

Activate a content part of the Accordion programmatically with the position zero-based index.

If the index is not specified, it defaults to zero, if it is an invalid index, eg. a string, nothing happens.

Requires jQuery core revision >= 557.

返回值

jQuery

参数

index (Number): An Integer specifying the zero-based index of the content to be activated. Defaults to 0.
示例

说明:

Activate the second content of the Accordion contained in <div id="accordion">.

jQuery 代码:

$('#accordion').activate(1);
说明:

Activate the first content of the Accordion contained in <ul id="nav">.

jQuery 代码:

$('#nav').activate();

8.2 Button
button(hash)

Creates a button from an image element.

This function attempts to mimic the functionality of the "button" found in modern day GUIs. There are two different 

buttons you can create using this plugin; Normal buttons, and Toggle buttons.

返回值

jQuery

参数

hash (hOptions): with options, described below. sPath Full path to the images, either relative or with full URL 

sExt Extension of the used images (jpg|gif|png) sName Name of the button, if not specified, try to fetch from id 

iWidth Width of the button, if not specified, try to fetch from element.width iHeight Height of the button, if not 

specified, try to fetch from element.height onAction Function to call when clicked / toggled. In case of a string, 

the element is wrapped inside an href tag. bToggle Do we need to create a togglebutton? (boolean) bState Initial 

state of the button? (boolean) sType Type of hover to create (img|css)

8.3 Center
center()

Takes all matched elements and centers them, absolutely, within the context of their parent element. Great for 

doing slideshows.

返回值

jQuery

示例

jQuery 代码:

$("div img").center();

8.4 Cookie
8.4.1 $.cookie(name)

Get the value of a cookie with the given name.

返回值

String

参数

name (String): The name of the cookie.
示例

说明:

Get the value of a cookie.

jQuery 代码:

$.cookie('the_cookie');

8.4.2 $.cookie(name, value, options)

Create a cookie with the given name and value and other optional parameters.

返回值

undefined

参数

name (String): The name of the cookie.
value (String): The value of the cookie.
options (Object): An object literal containing key/value pairs to provide optional cookie attributes.
Hash 选项

expires (Number|Date): Either an integer specifying the expiration date from now on in days or a Date object. If a 

negative value is specified (e.g. a date in the past), the cookie will be deleted. If set to null or omitted, the 

cookie will be a session cookie and will not be retained when the the browser exits.
path (String): The value of the path atribute of the cookie (default: path of page that created the cookie).
domain (String): The value of the domain attribute of the cookie (default: domain of page that created the cookie).
secure (Boolean): If true, the secure attribute of the cookie will be set and the cookie transmission will require 

a secure protocol (like HTTPS).
示例

说明:

Set the value of a cookie.

jQuery 代码:

$.cookie('the_cookie', 'the_value');
说明:

Create a cookie with all available options.

jQuery 代码:

$.cookie('the_cookie', 'the_value', {expires: 7, path: '/', domain: 'jquery.com', secure: true});
说明:

Create a session cookie.

jQuery 代码:

$.cookie('the_cookie', 'the_value');
说明:

Delete a cookie by setting a date in the past.

jQuery 代码:

$.cookie('the_cookie', '', {expires: -1});

8.5 Dimensions

8.5.1 height()

Returns the css height value for the first matched element. If used on document, returns the document's height 

(innerHeight) If used on window, returns the viewport's (window) height

返回值

Object

示例

jQuery 代码:

$("#testdiv").height()
结果:

"200px"
jQuery 代码:

$(document).height();
结果:

800
jQuery 代码:

$(window).height();
结果:

400

8.5.2 innerHeight()

Returns the inner height value (without border) for the first matched element. If used on document, returns the 

document's height (innerHeight) If used on window, returns the viewport's (window) height

返回值

Number

示例

jQuery 代码:

$("#testdiv").innerHeight()
结果:

800

8.5.3 innerWidth()

Returns the inner width value (without border) for the first matched element. If used on document, returns the 

document's Width (innerWidth) If used on window, returns the viewport's (window) width

返回值

Number

示例

jQuery 代码:

$("#testdiv").innerWidth()
结果:

1000

8.5.4 offset()

This returns an object with top, left, width, height, borderLeft, borderTop, marginLeft, marginTop, scrollLeft, 

scrollTop, pageXOffset, pageYOffset.

The top and left values include the scroll offsets but the scrollLeft and scrollTop properties of the returned 

object are the combined scroll offets of the parent elements (not including the window scroll offsets). This is not 

the same as the element's scrollTop and scrollLeft.

For accurate readings make sure to use pixel values.

返回值

Object

8.5.5 offset(refElement)

This returns an object with top, left, width, height, borderLeft, borderTop, marginLeft, marginTop, scrollLeft, 

scrollTop, pageXOffset, pageYOffset.

The top and left values include the scroll offsets but the scrollLeft and scrollTop properties of the returned 

object are the combined scroll offets of the parent elements (not including the window scroll offsets). This is not 

the same as the element's scrollTop and scrollLeft.

For accurate readings make sure to use pixel values.

返回值

Object

参数

refElement (String): This is an expression. The offset returned will be relative to the first matched element.


8.5.6 offset(refElement)

This returns an object with top, left, width, height, borderLeft, borderTop, marginLeft, marginTop, scrollLeft, 

scrollTop, pageXOffset, pageYOffset.

The top and left values include the scroll offsets but the scrollLeft and scrollTop properties of the returned 

object are the combined scroll offets of the parent elements (not including the window scroll offsets). This is not 

the same as the element's scrollTop and scrollLeft.

For accurate readings make sure to use pixel values.

返回值

Object

参数

refElement (jQuery): The offset returned will be relative to the first matched element.

8.5.7 offset(refElement)

This returns an object with top, left, width, height, borderLeft, borderTop, marginLeft, marginTop, scrollLeft, 

scrollTop, pageXOffset, pageYOffset.

The top and left values include the scroll offsets but the scrollLeft and scrollTop properties of the returned 

object are the combined scroll offets of the parent elements (not including the window scroll offsets). This is not 

the same as the element's scrollTop and scrollLeft.

For accurate readings make sure to use pixel values.

返回值

Object

参数

refElement (HTMLElement): The offset returned will be relative to this element.

8.5.8 outerHeight()

Returns the outer height value (including border) for the first matched element. Cannot be used on document or 

window.

返回值

Number

示例

jQuery 代码:

$("#testdiv").outerHeight()
结果:

1000

8.5.9 outerWidth()

Returns the outer width value (including border) for the first matched element. Cannot be used on document or 

window.

返回值

Number

示例

jQuery 代码:

$("#testdiv").outerWidth()
结果:

1000

8.5.10 scrollLeft()

Returns how many pixels the user has scrolled to the right (scrollLeft). Works on containers with overflow: auto 

and window/document.

返回值

Number

示例

jQuery 代码:

$("#testdiv").scrollLeft()
结果:

100

8.5.11 scrollTop()

Returns how many pixels the user has scrolled to the bottom (scrollTop). Works on containers with overflow: auto 

and window/document.

返回值

Number

示例

jQuery 代码:

$("#testdiv").scrollTop()
结果:

100

8.5.12 width()

Returns the css width value for the first matched element. If used on document, returns the document's width 

(innerWidth) If used on window, returns the viewport's (window) width

返回值

Object

示例

jQuery 代码:

$("#testdiv").width()
结果:

"200px"
jQuery 代码:

$(document).width();
结果:

800
jQuery 代码:

$(window).width();
结果:

400

8.6 Form

8.6.1 ajaxForm(object)

ajaxForm() provides a mechanism for fully automating form submission.

The advantages of using this method instead of ajaxSubmit() are:

1: This method will include coordinates for <input type="image" /> elements (if the element is used to submit 

the form). 2. This method will include the submit element's name/value data (for the element that was used to 

submit the form). 3. This method binds the submit() method to the form for you.

Note that for accurate x/y coordinates of image submit elements in all browsers you need to also use the 

"dimensions" plugin (this method will auto-detect its presence).

The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely passes the options 

argument along after properly binding events for submit elements and the form itself. See ajaxSubmit for a full 

description of the options argument.

返回值

jQuery

参数

object (options): literal containing options which control the form submission process
示例

说明:

Bind form's submit event so that 'myTargetDiv' is updated with the server response when the form is submitted.

jQuery 代码:

var options = { target: '#myTargetDiv' }; $('#myForm').ajaxSForm(options);
说明:

Bind form's submit event so that server response is alerted after the form is submitted.

jQuery 代码:

var options = { success: function(responseText) { alert(responseText); } }; $('#myForm').ajaxSubmit(options);
说明:

Bind form's submit event so that pre-submit callback is invoked before the form is submitted.

jQuery 代码:

var options = { beforeSubmit: function(formArray, jqForm) { if (formArray.length == 0) { alert('Please enter 

data.'); return false; } } }; $('#myForm').ajaxSubmit(options);

8.6.2 ajaxSubmit(object)

ajaxSubmit() provides a mechanism for submitting an HTML form using AJAX.

ajaxSubmit accepts a single argument which can be either a success callback function or an options Object. If a 

function is provided it will be invoked upon successful completion of the submit and will be passed the response 

from the server. If an options Object is provided, the following attributes are supported:

target: Identifies the element(s) in the page to be updated with the server response. This value may be specified 

as a jQuery selection string, a jQuery object, or a DOM element. default value: null

url: URL to which the form data will be submitted. default value: value of form's 'action' attribute

method:

返回值

jQuery

参数

object (options): literal containing options which control the form submission process
示例

说明:

Submit form and alert server response

jQuery 代码:

$('#myForm').ajaxSubmit(function(data) { alert('Form submit succeeded! Server returned: ' + data); });
说明:

Submit form and update page element with server response

jQuery 代码:

var options = { target: '#myTargetDiv' }; $('#myForm').ajaxSubmit(options);
说明:

Submit form and alert the server response

jQuery 代码:

var options = { success: function(responseText) { alert(responseText); } }; $('#myForm').ajaxSubmit(options);
说明:

Pre-submit validation which aborts the submit operation if form data is empty

jQuery 代码:

var options = { beforeSubmit: function(formArray, jqForm) { if (formArray.length == 0) { alert('Please enter 

data.'); return false; } } }; $('#myForm').ajaxSubmit(options);
说明:

json data returned and evaluated

jQuery 代码:

var options = { url: myJsonUrl.php, dataType: 'json', success: function(data) { // 'data' is an object representing 

the the evaluated json data } }; $('#myForm').ajaxSubmit(options);
说明:

XML data returned from server

jQuery 代码:

var options = { url: myXmlUrl.php, dataType: 'xml', success: function(responseXML) { // responseXML is XML document 

object var data = $('myElement', responseXML).text(); } }; $('#myForm').ajaxSubmit(options);
说明:

submit form and reset it if successful

jQuery 代码:

var options = { resetForm: true }; $('#myForm').ajaxSubmit(options);
说明:

Bind form's submit event to use ajaxSubmit

jQuery 代码:

$('#myForm).submit(function() { $(this).ajaxSubmit(); return false; });

8.6.3 clearForm()

Clears the form data. Takes the following actions on the form's input fields: - input text fields will have their 

'value' property set to the empty string - select elements will have their 'selectedIndex' property set to -1 - 

checkbox and radio inputs will have their 'checked' property set to false - inputs of type submit, button, reset, 

and hidden will not be effected - button elements will not be effected

返回值

jQuery

示例

说明:

Clears all forms on the page.

jQuery 代码:

$('form').clearForm();

8.6.4 clearInputs()

Clears the selected form elements. Takes the following actions on the matched elements: - input text fields will 

have their 'value' property set to the empty string - select elements will have their 'selectedIndex' property set 

to -1 - checkbox and radio inputs will have their 'checked' property set to false - inputs of type submit, button, 

reset, and hidden will not be effected - button elements will not be effected

返回值

jQuery

示例

说明:

Clears all inputs with class myInputs

jQuery 代码:

$('.myInputs').clearInputs();

8.6.5 fieldSerialize(true)

Serializes all field elements in the jQuery object into a query string. This method will return a string in the 

format: name1=value1&name2=value2

The successful argument controls whether or not serialization is limited to 'successful' controls (per 

http://www.w3.org/TR/html4/interact/forms.html#successful-controls). The default value of the successful argument 

is true.

返回值

String

参数

true (successful): if only successful controls should be serialized (default is true)
示例

说明:

Collect the data from all successful input elements into a query string

jQuery 代码:

var data = $("input").formSerialize();
说明:

Collect the data from all successful radio input elements into a query string

jQuery 代码:

var data = $(":radio").formSerialize();
说明:

Collect the data from all successful checkbox input elements in myForm into a query string

jQuery 代码:

var data = $("#myForm :checkbox").formSerialize();
说明:

Collect the data from all checkbox elements in myForm (even the unchecked ones) into a query string

jQuery 代码:

var data = $("#myForm :checkbox").formSerialize(false);
说明:

Collect the data from all successful input, select, textarea and button elements into a query string

jQuery 代码:

var data = $(":input").formSerialize();

8.6.6 fieldValue(successful)

Returns the value of the field element in the jQuery object. If there is more than one field element in the jQuery 

object the value of the first successful one is returned.

The successful argument controls whether or not the field element must be 'successful' (per 

http://www.w3.org/TR/html4/interact/forms.html#successful-controls). The default value of the successful argument 

is true. If this value is false then the value of the first field element in the jQuery object is returned.

Note: If no valid value can be determined the return value will be undifined.

Note: The fieldValue returned for a select-multiple element or for a checkbox input will always be an array if it 

is not undefined.

返回值

String or Array<String>

参数

successful (Boolean): true if value returned must be for a successful controls (default is true)
示例

说明:

Gets the current value of the myPasswordElement element

jQuery 代码:

var data = $("#myPasswordElement").formValue();
说明:

Get the value of the first successful control in the jQuery object.

jQuery 代码:

var data = $("#myForm :input").formValue();
说明:

Get the array of values for the first set of successful checkbox controls in the jQuery object.

jQuery 代码:

var data = $("#myForm :checkbox").formValue();
说明:

Get the value of the select control

jQuery 代码:

var data = $("#mySingleSelect").formValue();
说明:

Get the array of selected values for the select-multiple control

jQuery 代码:

var data = $("#myMultiSelect").formValue();

8.6.7 fieldValue(el, successful)

Returns the value of the field element.

The successful argument controls whether or not the field element must be 'successful' (per 

http://www.w3.org/TR/html4/interact/forms.html#successful-controls). The default value of the successful argument 

is true. If the given element is not successful and the successful arg is not false then the returned value will be 

null.

Note: The fieldValue returned for a select-multiple element will always be an array.

返回值

String or Array<String>

参数

el (Element): The DOM element for which the value will be returned
successful (Boolean): true if value returned must be for a successful controls (default is true)
示例

说明:

Gets the current value of the myPasswordElement element

jQuery 代码:

var data = jQuery.fieldValue($("#myPasswordElement")[0]);

8.6.8 
formSerialize(true)

Serializes form data into a 'submittable' string. This method will return a string in the format: 

name1=value1&name2=value2

The semantic argument can be used to force form serialization in semantic order. If your form must be submitted 

with name/value pairs in semantic order then pass true for this arg, otherwise pass false (or nothing) to avoid the 

overhead for this logic (which can be significant for very large forms).

返回值

String

参数

true (semantic): if serialization must maintain strict semantic ordering of elements (slower)
示例

说明:

Collect all the data from a form into a single string

jQuery 代码:

var data = $("#myForm").formSerialize(); $.ajax('POST', "myscript.cgi", data);

8.6.9 formToArray(true)

formToArray() gathers form element data into an array of objects that can be passed to any of the following ajax 

functions: $.get, $.post, or load. Each object in the array has both a 'name' and 'value' property. An example of 

an array for a simple login form might be:

[ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]

It is this array that is passed to pre-submit callback functions provided to the ajaxSubmit() and ajaxForm() 

methods.

The semantic argument can be used to force form serialization in semantic order. If your form must be submitted 

with name/value pairs in semantic order then pass true for this arg, otherwise pass false (or nothing) to avoid the 

overhead for this logic (which can be significant for very large forms).

返回值

Array<Object>

参数

true (semantic): if serialization must maintain strict semantic ordering of elements (slower)
示例

说明:

Collect all the data from a form and submit it to the server.

jQuery 代码:

var data = $("#myForm").formToArray(); $.post( "myscript.cgi", data );

8.6.10 resetForm()

Resets the form data. Causes all form elements to be reset to their original value.

返回值

jQuery

示例

说明:

Resets all forms on the page.

jQuery 代码:

$('form').resetForm();

8.7 Interface

8.7.1 $.recallDroppables()

Recalculate all Droppables

返回值

jQuery

示例

jQuery 代码:

$.recallDroppable();

8.7.2 $.SortSerialize()

This function returns the hash and an object (can be used as arguments for $.post) for every sortable in the page 

or specific sortables. The hash is based on the 'id' attributes of container and items.

返回值

String

参数

():

8.7.3 Draggable(hash)

Create a draggable element with a number of advanced options including callback, Google Maps type draggables, 

reversion, ghosting, and grid dragging.

返回值

jQuery

参数

hash (Hash): A hash of parameters. All parameters are optional.
Hash 选项

handle (String): The jQuery selector matching the handle that starts the draggable
handle (DOMElement): The DOM Element of the handle that starts the draggable
revert (Boolean): When true, on stop-drag the element returns to initial position
ghosting (Boolean): When true, a copy of the element is moved
zIndex (Integer): zIndex depth for the element while it is being dragged
opacity (Float): A number between 0 and 1 that indicates the opacity of the element while being dragged
grid (Integer): A number of pixels indicating the grid that the element should snap to
grid (Array): A number of x-pixels and y-pixels indicating the grid that the element should snap to
fx (Integer): Duration for the effect (like ghosting or revert) applied to the draggable
containment (String): Define the zone where the draggable can be moved. 'parent' moves it inside parent element, 

while 'document' prevents it from leaving the document and forcing additional scrolling
containment (Array): An 4-element array (topm left, width, height) indicating the containment of the element
axis (String): Set an axis: vertical (with 'vertically') or horizontal (with 'horizontally')
onStart (Function): Callback function triggered when the dragging starts
onStop (Function): Callback function triggered when the dragging stops
onChange (Function): Callback function triggered when the dragging stop and the element was moved at least one 

pixel
onDrag (Function): Callback function triggered while the element is dragged. Receives two parameters: x and y 

coordinates. You can return an object with new coordinates {x: x, y: y} so this way you can interact with the 

dragging process (for instance, build your containment)
insideParent (Boolean): Forces the element to remain inside its parent when being dragged (like Google Maps)
snapDistance (Integer): The element is not moved unless it is dragged more than snapDistance. You can prevent 

accidental dragging and keep regular clicking enabled (for links or form elements, for instance)
cursorAt (Object): The dragged element is moved to the cursor position with the offset specified. Accepts value for 

top, left, right and bottom offset. Basically, this forces the cursor to a particular position during the entire 

drag operation.
autoSize (Boolean): When true, the drag helper is resized to its content, instead of the dragged element's sizes

8.7.4 DraggableDestroy()

Destroy an existing draggable on a collection of elements

返回值

jQuery

示例

jQuery 代码:

$('#drag2').DraggableDestroy();

8.7.5 Droppable(options)

With the Draggables plugin, Droppable allows you to create drop zones for draggable elements.

参数

options (Hash): A hash of options
Hash 选项

accept (String): The class name for draggables to get accepted by the droppable (mandatory)
activeclass (String): When an acceptable draggable is moved, the droppable gets this class
hoverclass (String): When an acceptable draggable is inside the droppable, the droppable gets this class
tolerance (String): Choose from 'pointer', 'intersect', or 'fit'. The pointer options means that the pointer must 

be inside the droppable in order for the draggable to be dropped. The intersect option means that the draggable 

must intersect the droppable. The fit option means that the entire draggable must be inside the droppable.
onDrop (Function): When an acceptable draggable is dropped on a droppable, this callback is called. It passes the 

draggable DOMElement as a parameter.
onHover (Function): When an acceptable draggable is hovered over a droppable, this callback is called. It passes 

the draggable DOMElement as a parameter.
onOut (Function): When an acceptable draggable leaves a droppable, this callback is called. It passes the draggable 

DOMElement as a parameter.
示例

jQuery 代码:

$('#dropzone1').Droppable( { accept : 'dropaccept', activeclass: 'dropzoneactive', hoverclass: 'dropzonehover', 

ondrop: function (drag) { alert(this); //the droppable alert(drag); //the draggable }, fit: true } )

8.7.6 DroppableDestroy()

Destroy an existing droppable on a collection of elements

返回值

jQuery

示例

jQuery 代码:

$('#drag2').DroppableDestroy();

8.7.7 Sortable(options)

Allows you to resort elements within a container by dragging and dropping. Requires the Draggables and Droppables 

plugins. The container and each item inside the container must have an ID. Sortables are especially useful for 

lists.

参数

options (Hash): A hash of options
Hash 选项

accept (String): The class name for items inside the container (mandatory)
activeclass (String): The class for the container when one of its items has started to move
hoverclass (String): The class for the container when an acceptable item is inside it
helperclass (String): The helper is used to point to the place where the item will be moved. This is the class for 

the helper.
opacity (Float): Opacity (between 0 and 1) of the item while being dragged
ghosting (Boolean): When true, the sortable is ghosted when dragged
tolerance (String): Either 'pointer', 'intersect', or 'fit'. See Droppable for more details
fit (Boolean): When true, sortable must be inside the container in order to drop
fx (Integer): Duration for the effect applied to the sortable
onchange (Function): Callback that gets called when the sortable list changed. It takes an array of serialized 

elements
floats (Boolean): True if the sorted elements are floated
containment (String): Use 'parent' to constrain the drag to the container
axis (String): Use 'horizontally' or 'vertically' to constrain dragging to an axis
handle (String): The jQuery selector that indicates the draggable handle
handle (DOMElement): The node that indicates the draggable handle
onHover (Function): Callback that is called when an acceptable item is dragged over the container. Gets the 

hovering DOMElement as a parameter
onOut (Function): Callback that is called when an acceptable item leaves the container. Gets the leaving DOMElement 

as a parameter
cursorAt (Object): The mouse cursor will be moved to the offset on the dragged item indicated by the object, which 

takes "top", "bottom", "left", and "right" keys
onStart (Function): Callback function triggered when the dragging starts
onStop (Function): Callback function triggered when the dragging stops
示例

jQuery 代码:

$('ul').Sortable( { accept : 'sortableitem', activeclass : 'sortableactive', hoverclass : 'sortablehover', 

helperclass : 'sorthelper', opacity: 0.5, fit : false } )

8.7.8 SortableAddItem(elem)

A new item can be added to a sortable by adding it to the DOM and then adding it via SortableAddItem.

返回值

jQuery

参数

elem (DOMElement): A DOM Element to add to the sortable list
示例

jQuery 代码:

$('#sortable1').append('<li id="newitem">new item</li>') .SortableAddItem($("#new_item")[0])

8.8 Metadata

8.8.1 $.meta.setType(type, name)

Sets the type of metadata to use. Metadata is encoded in JSON, and each property in the JSON will become a property 

of the element itself.

There are three supported types of metadata storage:

attr: Inside an attribute. The name parameter indicates which attribute.

class: Inside the class attribute, wrapped in curly braces: { }

elem: Inside a child element (e.g. a script tag). The name parameter indicates which element.

The metadata for an element is loaded the first time the element is accessed via jQuery.

As a result, you can define the metadata type, use $(expr) to load the metadata into the elements matched by expr, 

then redefine the metadata type and run another $(expr) for other elements.

返回值

undefined

参数

type (String): The encoding type
name (String): The name of the attribute to be used to get metadata (optional)
示例

说明:

Reads metadata from the class attribute

HTML 代码:

$.meta.setType("class")
jQuery 代码:

<p id="one" class="some_class {item_id: 1, item_label: 'Label'}">This is a p</p>
说明:

Reads metadata from a "data" attribute

HTML 代码:

$.meta.setType("attr", "data")
jQuery 代码:

<p id="one" class="some_class" data="{item_id: 1, item_label: 'Label'}">This is a p</p>
说明:

Reads metadata from a nested script element

HTML 代码:

$.meta.setType("elem", "script")
jQuery 代码:

<p id="one" class="some_class"><script>{item_id: 1, item_label: 'Label'}</script>This is a 

p</p>

8.8.2 data()

Returns the metadata object for the first member of the jQuery object.

返回值

jQuery

8.9 Tabs

8.9.1 disableTab(position)

Disable a tab, so that clicking it has no effect.

返回值

jQuery

参数

position (Number): An integer specifying the position of the tab (no zero-based index) to be disabled. If this 

parameter is omitted, the first tab will be disabled.
示例

说明:

Disable the second tab of the tab interface contained in <div id="container">.

jQuery 代码:

$('#container').disableTab(2);

8.9.2 enableTab(position)

Enable a tab that has been disabled.

返回值

jQuery

参数

position (Number): An integer specifying the position of the tab (no zero-based index) to be enabled. If this 

parameter is omitted, the first tab will be enabled.
示例

说明:

Enable the second tab of the tab interface contained in <div id="container">.

jQuery 代码:

$('#container').enableTab(2);

8.9.3 tabs(initial, settings)

Create an accessible, unobtrusive tab interface based on a certain HTML structure.

The underlying HTML has to look like this:

<div id="container"> <ul> <li><a href="#section-1">Section 1</a></li> 

<li><a href="#section-2">Section 2</a></li> <li><a href="#section-3">Section 

3</a></li> </ul> <div id="section-1">

</div> <div id="section-2">

</div> <div id="section-3">

</div> </div>

Each anchor in the unordered list points directly to a section below represented by one of the divs (the URI in the 

anchor's href attribute refers to the fragment with the corresponding id). Because such HTML structure is fully 

functional on its own, e.g. without JavaScript, the tab interface is accessible and unobtrusive.

A tab is also bookmarkable via hash in the URL. Use the History/Remote plugin (Tabs will auto-detect its presence) 

to fix the back (and forward) button.

返回值

jQuery

参数

initial (Number): An integer specifying the position of the tab (no zero-based index) that gets first activated, 

e.g. on page load. If a hash in the URL of the page refers to one fragment (tab container) of a tab interface, this 

parameter will be ignored and instead the tab belonging to that fragment in that specific tab interface will be 

activated. Defaults to 1 if omitted.
settings (Object): An object literal containing key/value pairs to provide optional settings.
Hash 选项

disabled (Array<Number>): An array containing the position of the tabs (no zero-based index) that should be 

disabled on initialization. Default value: null.
bookmarkable (Boolean): Boolean flag indicating if support for bookmarking and history (via changing hash in the 

URL of the browser) is enabled. Default value: false, unless the History/Remote plugin is included. In that case 

the default value becomes true. @see $.ajaxHistory.initialize
fxFade (Boolean): Boolean flag indicating whether fade in/out animations are used for tab switching. Can be 

combined with fxSlide. Will overrule fxShow/fxHide. Default value: false.
fxSlide (Boolean): Boolean flag indicating whether slide down/up animations are used for tab switching. Can be 

combined with fxFade. Will overrule fxShow/fxHide. Default value: false.
fxSpeed (String|Number): A string representing one of the three predefined speeds ("slow", "normal", or "fast") or 

the number of milliseconds (e.g. 1000) to run an animation. Default value: "normal".
fxShow (Object): An object literal of the form jQuery's animate function expects for making your own, custom 

animation to reveal a tab upon tab switch. Unlike fxFade or fxSlide this animation is independent from an optional 

hide animation. Default value: null. @see animate
fxHide (Object): An object literal of the form jQuery's animate function expects for making your own, custom 

animation to hide a tab upon tab switch. Unlike fxFade or fxSlide this animation is independent from an optional 

show animation. Default value: null. @see animate
fxShowSpeed (String|Number): A string representing one of the three predefined speeds ("slow", "normal", or "fast") 

or the number of milliseconds (e.g. 1000) to run the animation specified in fxShow. Default value: fxSpeed.
fxHideSpeed (String|Number): A string representing one of the three predefined speeds ("slow", "normal", or "fast") 

or the number of milliseconds (e.g. 1000) to run the animation specified in fxHide. Default value: fxSpeed.
fxAutoHeight (Boolean): Boolean flag that if set to true causes all tab heights to be constant (being the height of 

the tallest tab). Default value: false.
onClick (Function): A function to be invoked upon tab switch, immediatly after a tab has been clicked, e.g. before 

the other's tab content gets hidden. The function gets passed three arguments: the first one is the clicked tab 

(e.g. an anchor element), the second one is the DOM element containing the content of the clicked tab (e.g. the 

div), the third argument is the one of the tab that gets hidden. Default value: null.
onHide (Function): A function to be invoked upon tab switch, immediatly after one tab's content got hidden (with or 

without an animation) and right before the next tab is revealed. The function gets passed three arguments: the 

first one is the clicked tab (e.g. an anchor element), the second one is the DOM element containing the content of 

the clicked tab, (e.g. the div), the third argument is the one of the tab that gets hidden. Default value: null.
onShow (Function): A function to be invoked upon tab switch. This function is invoked after the new tab has been 

revealed, e.g. after the switch is completed. The function gets passed three arguments: the first one is the 

clicked tab (e.g. an anchor element), the second one is the DOM element containing the content of the clicked tab, 

(e.g. the div), the third argument is the one of the tab that gets hidden. Default value: null.
selectedClass (String): The CSS class attached to the li element representing the currently selected (active) tab. 

Default value: "tabs-selected".
disabledClass (String): The CSS class attached to the li element representing a disabled tab. Default value: "tabs

-disabled".
hideClass (String): The CSS class used for hiding inactive tabs. A class is used instead of "display: none" in the 

style attribute to maintain control over visibility in other media types than screen, most notably print. Default 

value: "tabs-hide".
tabStruct (String): A CSS selector or basic XPath expression reflecting a nested HTML structure that is different 

from the default single div structure (one div with an id inside the overall container holds one tab's content). If 

for instance an additional div is required to wrap up the several tab containers such a structure is expressed by 

"div>div". Default value: "div".
示例

说明:

Create a basic tab interface.

jQuery 代码:

$('#container').tabs();
说明:

Create a basic tab interface with the second tab initially activated.

jQuery 代码:

$('#container').tabs(2);
说明:

Create a tab interface with the third and fourth tab being disabled.

jQuery 代码:

$('#container').tabs({disabled: [3, 4]});
说明:

Create a tab interface that uses slide down/up animations for showing/hiding tab content upon tab switching.

jQuery 代码:

$('#container').tabs({fxSlide: true});

8.9.4 triggerTab(position)

Activate a tab programmatically with the given position (no zero-based index), as if the tab itself were clicked.

返回值

jQuery

参数

position (Number): An integer specifying the position of the tab (no zero-based index) to be activated. If this 

parameter is omitted, the first tab will be activated.
示例

说明:

Activate the second tab of the tab interface contained in <div id="container">.

jQuery 代码:

$('#container').triggerTab(2);
说明:

Activate the first tab of the tab interface contained in <div id="container">.

jQuery 代码:

$('#container').triggerTab(1);
说明:

Activate the first tab of the tab interface contained in <div id="container">.

jQuery 代码:

$('#container').triggerTab();

8.10 Tooltip
Tooltip(settings)

Display a customized tooltip instead of the default one for every selected element. The tooltip behaviour mimics 

the default one, but lets you style the tooltip and specify the delay before displaying it.

In addition, it displays the href value, if it is available.

To style the tooltip, use these selectors in your stylesheet:

#tooltip - The tooltip container

#tooltip h3 - The tooltip title

#tooltip p.body - The tooltip body, shown when using showBody

#tooltip p.url - The tooltip url, shown when using showURL

返回值

jQuery

参数

settings (Object): (optional) Customize your Tooltips
Hash 选项

delay (Number): The number of milliseconds before a tooltip is display, default is 250
event (String): The event on which the tooltip is displayed, default is "mouseover", "click" works fine, too
track (Boolean): If true, let the tooltip track the mousemovement, default is false
showURL (Boolean): If true, shows the href or src attribute within p.url, default is true
showBody (String): If specified, uses the String to split the title, displaying the first part in the h3 tag, all 

following in the p.body tag, separated with <br/>s, default is null
extraClass (String): If specified, adds the class to the tooltip helper, default is null
fixPNG (Boolean): If true, fixes transparent PNGs in IE, default is false
示例

说明:

Shows tooltips for anchors, inputs and images, if they have a title

jQuery 代码:

$('a, input, img').Tooltip();
说明:

Shows tooltips for labels with no delay, tracking mousemovement, displaying the tooltip when the label is clicked.

jQuery 代码:

$('label').Tooltip({ delay: 0, track: true, event: "click" });
说明:

This example starts with modifying the global settings, applying them to all following Tooltips; Afterwards, 

Tooltips for anchors with class pretty are created with an extra class for the Tooltip: "fancy" for anchors, 

"fancy-img" for images

jQuery 代码:

// modify global settings $.extend($.fn.Tooltip.defaults, { track: true, delay: 0, showURL: false, showBody: " - ", 

fixPNG: true }); // setup fancy tooltips $('a.pretty').Tooltip({ extraClass: "fancy" }); $('img.pretty').Tooltip({ 

extraClass: "fancy-img", });