`
收藏列表
标题 标签 来源
EL 读取Boolean属性时返回为空 http://stackoverflow.com/questions/5697589/cannot-read-boolean-property-in-jsp-el
If an object property is declared as of type Boolean (not primitive boolean) then there seem to be a problem in EL recognizing it!

Say you have the following object

class Case{
     private Boolean  valid;

     public Boolean isValid(){
         return this.valid;
     }

     public void setValid(Boolean val){
         this.valid = val;
     }
}
Say we put an object of type Case in the request under the name "case", then I try this in the JSP:

<td>Object is ${case.valid ? "Valid":"Invalid"} </td>
This gives me error "valid" is not a property of object Case! If I change valid from Boolean to primitive boolean it works!

Is this a known problem with Boolean types in EL that they are not recognized as boolean but as Java "normal" objects? What is the proper way to handle this?

Thanks


EL treats Boolean as an object (which is totally correct) so it looks for getValid() method. This is consistent with JavaBeans specification.

Try changing your property from Boolean reference type to boolean primitive type. If this is not possible and you're using new EL (i.e. 2.2 - I'm not sure about 2.1) you can invoke a method, so ${case.isValid()} would be an example of a correct usage of this new EL feature.

对照表
http://wiki.apache.org/tomcat/Specifications

JSTL 标签接口及实现
http://jstl.java.net/download.html
其中tomcat也有对JSTL的实现,jasper.jsr包
JSTL 文档
http://docs.oracle.com/javaee/5/tutorial/doc/bnaiy.html
id包含特殊字符,会导致内存泄漏
<html>
    <head>
        <script type="text/javascript" src="jquery-1.8.3.js"></script>
    </head>
    <body>
    	<button onclick="add()">add</button>
		<button onclick="del()">del</button>
		<span id="foo:bar">FOO:BAR</span>  
		<span id="foo[bar]">foo[bar]</span>  
		<span id="foo.bar">foo.bar</span>
    </body>
    <script type="text/javascript">
    	console.log($("#foo:bar"));
        var iframes = [];
		function add() {
			var iframe = document.createElement("iframe");
			iframe.id="hello.id.b";
			iframe.src ="www.huawei.com";
			document.body.appendChild(iframe);
			iframes.push(iframe);
		}
		function del() {
			var iframe = iframes.pop();
			if(iframe) {
				document.body.removeChild(iframe);
				iframe = null;
			}
		}
    </script>
</html>

元素id中不要带有特殊字符,否则采用jquery选择器是选择不到的,这会导致内存泄漏
MVC 的原理 http://heim.ifi.uio.no/~trygver/themes/mvc/mvc-index.html
问题:
1、Model 只是数据吗,是bean?;View 只是界面吗,是HTML?
python selenium
from selenium import selenium
import time

class test():
    def __init__(self):
        pass
    def OpenBrower(self, browertype, url, uri):
        self.selenium = selenium("localhost","4445",browertype,url)
        sel = self.selenium
        sel.start()
        sel.open(uri)
    def Search(self,content):
        sel = self.selenium
        sel.type("id=kw",content)
        time.sleep("30000")
    def CloseBrower(self):
        sel = self.selenium
        sel.close()    
if __name__ == "__main__":
    sel = test()
    sel.OpenBrower("*firefox","www.baidu.com","/")
    sel.Search("123,tdp")

出现如下错误
Traceback (most recent call last):
  File "C:\Users\TDP\Desktop\test.py", line 21, in <module>
    sel.OpenBrower("*firefox","www.baidu.com","/")
  File "C:\Users\TDP\Desktop\test.py", line 10, in OpenBrower
    sel.start()
  File "D:\selenium-2.28.0\py\selenium\selenium.py", line 189, in start
    result = self.get_string("getNewBrowserSession", start_args)
  File "D:\selenium-2.28.0\py\selenium\selenium.py", line 223, in get_string
    result = self.do_command(verb, args)
  File "D:\selenium-2.28.0\py\selenium\selenium.py", line 217, in do_command
    raise Exception, data
Exception: Failed to start new browser session: Error while launching browser

原因:URL地址错误sel.OpenBrower("*firefox","www.baidu.com","/")改为sel.OpenBrower("*firefox","http://www.baidu.com","/")


附:支持的浏览器
Supported browsers include:
  *firefox
  *mock
  *firefoxproxy
  *pifirefox
  *chrome
  *iexploreproxy
  *iexplore
  *firefox3
  *safariproxy
  *googlechrome
  *konqueror
  *firefox2
  *safari
  *piiexplore
  *firefoxchrome
  *opera
  *webdriver
  *iehta
  *custom
jquery 类的设计思路

        
为什么 FreeMarker 打印奇怪的数字数字格式(比如 1,000,000 或 1 000 000 而不是 1000000)?
5.  为什么 FreeMarker 打印奇怪的数字数字格式(比如
1,000,000 或 1 000 000 而不是 1000000)?
FreeMarker 使用 Java 平台的本地化敏感的数字格式信息。默认的本地化数字格式可能
是分组或其他不想要的格式。为了避免这种情况,你不得不使用 number_format 设置
来重写 Java 平台建议的数字格式,比如:
注意人们通常在没有分组分隔符时阅读大数是有些困难的。所以通常建议保留分隔符,
而在对计算机处理时的情况,分组分隔符会使其混乱,就要使用内建函数 c 了。比如:
cfg.setNumberFormat("0.######");  // now it will print 1000000
// where cfg is a freemarker.template.Configuration object
<a href="/shop/productdetails?id=${product.id?c}">Details...</a>
js 相加
"aaaa"+4625196817309499395 = ?
URL ""引号的转义
var name = "<c:out value='${name}' escapeXml='true'></c:out>"

采用<c:out>标签, 设置 escapeXml='true' 属性
W3C 技术标准网站
1、CSS
http://www.w3.org/Style/CSS/current-work
W3C 发布 CSS 选择器 API 规范
Selectors API Level 1
http://www.w3.org/TR/2012/WD-selectors-api-20120628/
The following features are defined in the DOM Level 3 Core specification [DOM-LEVEL-3-CORE]:

Document interface.
DocumentFragment interface.
Element interface.
NodeList interface.

Interface Definitions

partial interface Document {
  Element?  querySelector(DOMString selectors);
  NodeList  querySelectorAll(DOMString selectors);
};

partial interface DocumentFragment {
  Element?  querySelector(DOMString selectors);
  NodeList  querySelectorAll(DOMString selectors);
};

partial interface Element {
  Element?  querySelector(DOMString selectors);
  NodeList  querySelectorAll(DOMString selectors);
};

Selectors API Level 2
http://www.w3.org/TR/2012/WD-selectors-api2-20120628/

Interface Definitions

partial interface Document {
  Element?  querySelector(DOMString selectors);
  NodeList  querySelectorAll(DOMString selectors);

  Element?  find(DOMString selectors, optional (Element or sequence<Node>)? refNodes);
  ?         findAll(DOMString selectors, optional (Element or sequence<Node>)? refNodes);
};

partial interface DocumentFragment {
  Element?  querySelector(DOMString selectors);
  NodeList  querySelectorAll(DOMString selectors);

  Element?  find(DOMString selectors, optional (Element or sequence<Node>)? refNodes);
  ?         findAll(DOMString selectors, optional (Element or sequence<Node>)? refNodes);
};

partial interface Element {
  Element?  querySelector(DOMString selectors);
  NodeList  querySelectorAll(DOMString selectors);

  Element?  find(DOMString selectors);
  ?         findAll(DOMString selectors);

  boolean   matches(DOMString selectors, optional (Element or sequence<Node>)? refNodes);
};

多了一个matches API

新增加了一个伪类: The :scope Pseudo-Class
jsp 自定义标签 与EL表达式的使用
1、定义标签描述文件(tld)  , .tld文件放置在WEB-INF下面,不需要在web.xml中用<jsp-config>去配置
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0">

    <description>dsl</description>
    <tlib-version>1.0</tlib-version>
    <jsp-version>2.0</jsp-version>
    <short-name>test</short-name>
    <uri>http://www.test.com/test</uri>
    <function>
        <name>hasRight</name>
        <function-class>com.test.web.irm.utils.IAMOperationUtil</function-class>
        <function-signature>
            boolean isUserHasPrivilege(java.lang.String)
        </function-signature>
    </function>
</taglib>

2、前缀 自动引用:  
	<jsp-config>
		<jsp-property-group>
			<url-pattern>*.usl</url-pattern>
			<el-ignored>false</el-ignored>
			<page-encoding>UTF-8</page-encoding>
			<scripting-invalid>false</scripting-invalid>
			<include-prelude>/WEB-INF/commontag.usl</include-prelude>
		</jsp-property-group>
	</jsp-config>
     commontag.tld文件内容如下:
     <%@ taglib prefix="test" uri="http://www.test.com/test" %>

3、EL表达式的使用:
${!test:hasRight('TEST_PHYDEV')}

spring 字符编码过滤器
配置至web.xml中
<filter>  
        <filter-name>encodingFilter</filter-name>  
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
        <init-param>  
            <param-name>encoding</param-name>  
            <param-value>UTF-8</param-value>  
        </init-param>  
        <init-param>  
            <param-name>forceEncoding</param-name>  
            <param-value>true</param-value>  
        </init-param>  
</filter>  
<filter-mapping>  
        <filter-name>encodingFilter</filter-name>  
        <url-pattern>*.html</url-pattern>  
</filter-mapping>  
<filter-mapping>  
        <filter-name>encodingFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
</filter-mapping>
css overflow http://www.qianduan.net/css-overflow-property.html
一个块级元素的内容超过了其大小, 不会影响到文档流


根据CSS的盒模型概念,页面中的每个元素,都是一个矩形的盒子。这些盒子的大小、位置和行为都可以用CSS来控制。对于行为,我的意思是当盒子内外的内容改变的时候,它如何处理。比如,如果你没有设置一个盒子的高度,该盒子的高度将会根据它容纳内容的需要而增长。但是当你给一个盒子指定了一个高度或宽度而里面的内容超出的时候会发生什么?这就是该添加CSS的overflow属性的时候了,它允许你设定该种情况下如何处理。
overflow属性有四个值:visible (默认), hidden, scroll, 和auto。同样有两个overflow的姐妹属性overflow-y 和overflow-x,它们很少被采用。
让我们分别看一下这几个值,并讨论一写共同用法和技巧。
Visible

如果你不设置overflow属性,则默认的overflow属性值就是visible。所以一般而言,并没有什么理由特别的设定overflow的属性为visible除非你想覆盖它在其它地方被设定的值。

这里需要记住的重要的事情是,尽管盒子外面的内容是可见的,内容并不会影响页面的工作流。比如:

一般来说,你至少不用为里面的内容为文字的盒子设置固定的高度,这样就不会遇到这种情况了。
Hidden

默认值visible的相反的值就是hidden。它会将所有超出盒子的所有内容都给隐藏掉。

这对应付使用动态的内容,而且可能会由于内容溢出而引起一些布局上的问题的确很有用。尽管如此,请记住用此方法隐藏的内容将彻底的看不到(除非去查看源代码)。 比如有的用户设置他们的浏览器的默认字体比你预期的要大些,你会将一些文字推到盒子的外面然后完全的隐藏之……
Scroll

设置一个盒子的overflow值为scroll将会隐藏掉渲染到盒子之外的内容,但是它将会提供一个滚动条在盒子内部滚动,从而可以查看剩下的内容。

值得注意的是,使用scroll将会同时产生水平和垂直两个滚动条,就算内容只需要其中一个。
Auto

overflow的auto值很像scroll,它唯一解决的是在你不需要的时候也会出现滚动条的问题。

清除浮动

设置overflow的一个更流行的用处是,说也奇怪,清除浮动。设置overflow并不会在该元素上清除浮动,它将清除自己(self-clear)。意思就是,应用了overflow(auto或hidden)的元素,将会扩展到它需要的大小以包围它里面的浮动的子元素(而不是叠了起来(collapsing)),假设未定义高度。就像这样:

对于此问题,经过测试,IE6会自动扩展父层元素的高度,而IE8和FF等浏览器加上overflow:auto后,即可清除浮动。——神飞
这里有更多关于浮动的细节文章关于浮动的一切。
跨浏览器的烦恼

就像CSS中的很多东东,overflow有很多的跨浏览器的蹊跷的事情。比如这些:
滚动条在盒子里面还是外面?

Firefox将其放到盒子外面,而IE则将其放到里面。我认为只有IE是对的(它应该在里面的)。

看清楚这个明显的不同。
IE 8 扩展盒子的bug

IE8有很多有趣的新bug,包括一些非常严重的隐藏在网页中的。这里有更多的关于IE8的overflow的bug的介绍。
破坏浮动布局

IE 6, 7 和 8都会扭曲默认的overflow visible值并将水平的扩展一个盒子一匹配内容(比如图片)。 这对使用浮动列布局的结构非常痛苦,而且单个扩展的列就能够将其它列挤下去并使布局乱掉!

事实上,这个我在验证的时候发现,只有IE6才会出现这种情况,而IE7、IE8和其它浏览器表现一致。如果大家在使用IE7或IE8时有遇到这种情况,请告诉我,多谢!——神飞
滚动条能用CSS控制吗?

IE过去在较老的版本中允许这样,但是之后就收敛了。比如许多表单元素,滚动条就不允许使用CSS控制。我在它是否是件好事情上没有任何具体的意见,但是我可以说,在网站的所有内容上使用滚动条是很丑陋的和俗气的。如果你需要一个美化的滚动条,你或许需要寻找JavaScript来模拟。
IE 技巧

无论是否需要,IE都会一直显示一个垂直的滚动条,这对预防水平跳动是有些作用的,但并非总是可取的。要想在IE中移除它,可以在body元素中设置overflow为auto。PS:此种情况也较少发现,不过在body的样式中添加overflow:auto的方法,建议考虑采用——神飞
演示

本文的演示页面,可以查看这个页面。






<!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=utf-8" />
<title>无标题文档</title>
<style>
#header {
	width: 700px;
	height: 200px;
	border:1px solid #0FF;
}

#content {
	width: 500px;
	height: 500px;
	float:left;
	border: 1px solid #96C;
	overflow:hidden;
}

.content_length {
	width: 900px;
	border: 1px solid #0F0;
	height: 700px;
}

#footer {
	/*clear:left;*/
	float:left;
	width: 200px;
	height: 200px;
	border:1px solid #F66;
}
</style>
</head>

<body>
<div id="header"></div>
<div id="content">
  <div class="content_length"></div>
</div>
<div id="footer"></div>
</body>
</html>
text-align属性
text-align应用于块级元素和内联元素效果是不同的。

当应用于块级元素,元素的文本节点居中

当用于内联元素,则内联元素居中同时内联元素的文本节点也在内联元素中居中

如:

<!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=utf-8" />
<title>无标题文档</title>
<style>
* {
	margin: 0;
	padding:0;
}
</style>
</head>
<body>
<div style="width: 100%; height: 100px; margin:40px 0 0 0; text-align:center; border: 1px solid #0F3">
  <div style="display:inline-block;  width: 50%; border:1px solid #F0F; height: 50%; line-height:50px;">adfa</div>
  <div style="display:inline-block; width: 50%; border:1px solid #909; height: 50%">asdfasdf</div>
</div>

<div style="width: 100%; height: 100px; margin:40px 0 0 0;  border: 1px solid #0F3">
  <div style="display:inline-block;  width: 50%; border:1px solid #F0F; height: 50%; line-height:50px; text-align:center;">adfa</div>
  <div style="display:inline-block; width: 50%; border:1px solid #909; height: 50%">asdfasdf</div>
</div>
</body>
</html>
让文本上下居中 line-height
设置line-height值与div高度值一样,则会在div中上下居中显示

<div style="border:1px solid #00F">
	<span style="width: 90px; height: 100px; line-height:90px">1234567</span>  <!-- line-height设置成与div一样的高度,则文本会上下居中-->
</div>
CSS display
display 在CSS 1中
Value: block | inline | list-item | none
Initial: block
Applies to: all elements
Inherited: no
Percentage values: N/A

block , 块: 独占一行, 可以设置宽高
inline,内联:设置高度和宽度无效,不占据行,可以设置其它盒模型属性(注:margin 上下外边距无效)。
list-item, 列表:就像li一样显示

http://www.w3.org/TR/2011/NOTE-css-2010-20110512/#css2
CSS 2.1中
inline-block, 内联块: 可以设置高度和宽度,但是不占据行。以内联元素来显示一行,可以运用块属性。


如:
<div style="border:1px solid #0F6">
	<div style="display:inline-block; height: 40px; width: 120px; border:1px solid #00F; background-color:#FC9; line-height:40px; margin: 400px;">asdfasfasdfasdfasf</div>
    <span style="border: 1px solid #C3C; background-color:#0F0; margin: 100px;">asdfasdfasdf</span>
</div>
CSS Position定位
CSS中 Position有四种定位

1、static 静态定位,浏览器默认的文档流显示形式。块级元素独占一行,行内元素平辅一行直到占满一行后才换行(注:浏览器为块级元素和行内元素定义了默认样式)

2、relative 相对定位, 参照点位于它在正常文档流中的位置的盒模型的左上方(注意是边框的左上方而不是margin的左上方)。top , right , bottom, left 是相对于这个参照点的偏移量。虽然它偏移了,但它所占的文档流位置不会移走.

3、absolute 绝对定位, 默认定位环境是body,即参照点是body的左上方,如果其祖先元素的position属性设置为relative,则该祖先元素成为这个元素的定位环境, 参照点仍是这个祖先元素的盒模型的左上方(边框的左上方而不是margin的左上方), 这种定位会把元素完全移出文档流,就像将该元素从父元素中删除了一样。

4、fixed 固定定位,定位环境是视口(即:浏览器中显示网页的小窗口)或者手持设备的屏幕,因此当页面滚动时固定定位的元素不会随子移动。 这种定位会把元素完全移出文档流。
CSS 盒模型
盒模型由外边距、边框、内边距、内容。
使用CSS 可以调整元素盒子的3个方面:
边框: 设置边框的粗细、样式、颜色
外边距:设置盒子与相邻元素之间的距离
内边距:设置盒子的内容与其边框之间的距离

理解:外边距会从边框开始向外推开相邻的元素,内边距会从边框开始向内推开元素中的内容。

1、盒子到底有多大:
盒子的大小是宽度+边框+内边距大小的矩形框。即:尽管我们认为盒子的边框和内边距应该处于内部,因而不会增大盒子的宽度,但事实上边框和内边距会增大盒子的宽度。width属性并不是盒子的宽度。

2、垂直的外边距折叠(块级元素)

3、通过在css开头关闭margin 和 padding 
* {
	margin: 0;
	padding:0;
}
获取,修改CSS样式, 自定义事件类型
<style>
#styleCss {
	border:1px;
	border-color:red;
	border-style:solid;
}
</style>
<style>
#innerCss {
	border:1px;
	border-color:green;
	border-style:solid;
}
</style>
<body>
	<div id="styleCss" style="height:100px;">dasdf</div>
	<div id="innerCss" style="height:100px;">asdfasdf</div>
	<!--http://javascript.gakaa.com/tips-changecssstyledynamically.aspx -->
	<script type="text/javascript">
		var dom = document.getElementById("styleCss");
		//通过style是访问不到定义在<style>和CSS文件中的样式的,只能获取定义在标签内style属性中的样式,如果属性值中间有横线,则采用骆驼命名法。
		console.log(dom.style.borderColor);   
		console.log(dom.style.getPropertyCSSValue("height"));
		
		//可以访问到style sheet中的样式。
		alert(window.getComputedStyle(dom,null).color)
		
		//自定义事件类型
		if(document.createEvent) {	
		
		    /**
			 *@param eventType 
                     String constant for one of the support event categories: 
					 HTMLEvents, 
					 KeyEvents (supported by Netscape 6, but not specified until DOM Level 3), 
					 MouseEvents, 
					 MutationEvents, 
					 UIEvents.
	          */
			var myevent = document.createEvent("HTMLEvents");			
            myevent.initEvent("myevent", true, true);             
			dom.addEventListener("myevent",clc);			
			dom.dispatchEvent(myevent);
		}
		else {
			console.log("document.createEvent in not a function")
		}
		
		function clc(evt) {
			alert(evt.target.tagName);			
		}	
		
		
		//修改style sheet中的值
		var allCSSRules = document.styleSheets[1].cssRules;
        var innerCss = allCSSRules[0].style;
		console.log(innerCss.borderColor = "red");
	</script>	
eclipse 中反编译插件的安装方法 jode decompiler
启动eclipse,help -> Software Updates-> Find and Install... -> Search for new features to install,单击"New Remote Site..." 在URL栏输入 http://www.technoetic.com/eclipse/update然后下一步,就可以看到“jode decompiler plugin *.*”,选上安装就可以了。安装好后可以看到Window -> Preferences...-> Java -> Jode Decompiler选项卡,okay,安装成功了。 



配置:Window-> Preferences... -> General -> Editors -> File Associations找到"*.class"在"Associated editors"里面可以看到"Jode class file viewer"选中它再单击Default按钮. 
js Event properties http://www.quirksmode.org/js/events_properties.html
What is the type of the event?
Which HTML element is the target of the event?
Which key was pressed during the event?
Which mouse button was pressed during the event?
What was the mouse position during the event?


On this page I give some example scripts for reading out event properties. There are very serious browser incompatibilities in this area.

As soon as we want to read out information about the event, we’re inundated by an immense amount of properties, most of which do not work in most browsers. See the Event compatibility tables for a quick overview or the W3C DOM Compatibility - Events page for a complete overview.

I am not going to give an alphabetical list of properties, since it wouldn’t help a bit to make you understand all this — the situation is too confusing. Instead I’ve written five scripts to ask five questions of the browser.

What is the type of the event?
Which HTML element is the target of the event?
Which key was pressed during the event?
Which mouse button was pressed during the event?
What was the mouse position during the event?
I answered the last question in great detail in a now outdated Evolt article.

Please note that in these scripts I’ve been very strict in my object detection. I first create cross-browser event access, then I check if the browser supports each individual property before using it.

What is the type of the event?

This is the only question with a true cross-browser answer: use the type property to read out the type:

function doSomething(e) {
	if (!e) var e = window.event;
	alert(e.type);
}
Which HTML element is the target of the event?

W3C/Netscape says: the target. No, says Microsoft, the srcElement. Both properties return the HTML element the event took place on.

function doSomething(e) {
	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
}
The last two lines of code are especially for Safari. If an event takes place on an element that contains text, this text node, and not the element, becomes the target of the event. Therefore we check if the target's nodeType is 3, a text node. If it is we move to its parent node, the HTML element.

Even if an event is captured or bubbles up, the target/srcElement always remains the element the event took place on.

Other targets

There are some more targeting properties. I discuss currentTarget on the Event order page and relatedTarget, fromElement and toElement on the Mouse events page.

Which key has been pressed?

This one is relatively easy. First get the code of the key (a = 65) from the keyCode property.

When you’ve read out the key code, send it through the method String.fromCharCode() to obtain the actual key value, if necessary.

function doSomething(e) {
	var code;
	if (!e) var e = window.event;
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	var character = String.fromCharCode(code);
	alert('Character was ' + character);
}
There are some subtleties that may make the key events hard to use. For instance, the keypress event fires as long as the user keeps the key pressed. However, in most browsers the keydown event also keeps firing as long as the key is pressed. I’m not sure this is a good idea, but it’s what happens.

Which mouse button has been clicked?

There are two properties for finding out which mouse button has been clicked: which and button. Please note that these properties don’t always work on a click event. To safely detect a mouse button you have to use the mousedown or mouseup events.

which is an old Netscape property. Left button gives a value of 1, middle button (mouse wheel) gives 2, right button gives 3. No problems, except its meager support (and the fact that it’s also used for key detection).

Now button has been fouled up beyond all recognition. According to W3C its values should be:

Left button – 0
Middle button – 1
Right button – 2
According to Microsoft its values should be:

Left button – 1
Middle button – 4
Right button – 2
No doubt the Microsoft model is better than W3C’s. 0 should mean “no button pressed”, anything else is illogical.

Besides, only in the Microsoft model button values can be combined, so that 5 would mean “left and middle button”. Not even Explorer 6 actually supports this yet, but in the W3C model such a combination is theoretically impossible: you can never know whether the left button was also clicked.

In my opinion W3C has made some serious mistakes in defining button.

Right click

Fortunately you most often want to know if the right button has been clicked. Since W3C and Microsoft happen to agree on this one and give button a value of 2, you can still detect a right click.

function doSomething(e) {
	var rightclick;
	if (!e) var e = window.event;
	if (e.which) rightclick = (e.which == 3);
	else if (e.button) rightclick = (e.button == 2);
	alert('Rightclick: ' + rightclick); // true or false
}
Please note that, although Macs have only one mouse button, Mozilla gives a Ctrl–Click a button value of 2, since Ctrl–Click also brings up the context menu. iCab doesn’t yet support mouse button properties at all and you cannot yet detect a right–click in Opera.

Mouse position

As to the mouse position, the situation is horrible. Although there are no less than six mouse coordinates property pairs, there is no reliable cross–browser way to find the mouse coordinates relative to the document we need.

These are the six property pairs — see also the Event compatibility tables or the W3C DOM Compatibility - Events page.

clientX,clientY
layerX,layerY
offsetX,offsetY
pageX,pageY
screenX,screenY
x,y
I explained the problem, W3C’s vagueness and the use of pageX/Y and clientX/Y in my slightly outdated Evolt article.

The screenX and screenY properties are the only ones that are completely cross–browser compatible. They give the mouse position relative to the entire computer screen of the user. Unfortunately this information is completely useless: you never need to know the mouse position relative to the screen — well, maybe only if you want to place another window at the mouse position.

The other three property pairs are unimportant. See the W3C DOM Compatibility - Events page for a description.

Correct script

This is the correct script for detecting the mouse coordinates:

function doSomething(e) {
	var posx = 0;
	var posy = 0;
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
	// posx and posy contain the mouse position relative to the document
	// Do something with this information
}
js event order js event http://www.quirksmode.org/js/events_order.html
On the Introduction to events page I asked a question that at first sight seems incomprehensible: “If an element and one of its ancestors have an event handler for the same event, which one should fire first?” Not surprisingly, this depends on the browser.

The basic problem is very simple. Suppose you have a element inside an element

-----------------------------------
| element1                        |
|   -------------------------     |
|   |element2               |     |
|   -------------------------     |
|                                 |
-----------------------------------
and both have an onClick event handler. If the user clicks on element2 he causes a click event in both element1 and element2. But which event fires first? Which event handler should be executed first? What, in other words, is the event order?

Two models

Not surprisingly, back in the bad old days Netscape and Microsoft came to different conclusions.

Netscape said that the event on element1 takes place first. This is called event capturing.
Microsoft maintained that the event on element2 takes precedence. This is called event bubbling.
The two event orders are radically opposed. Explorer only supports event bubbling. Mozilla, Opera 7 and Konqueror support both. Older Opera's and iCab support neither.

Event capturing

When you use event capturing

               | |
---------------| |-----------------
| element1     | |                |
|   -----------| |-----------     |
|   |element2  \ /          |     |
|   -------------------------     |
|        Event CAPTURING          |
-----------------------------------
the event handler of element1 fires first, the event handler of element2 fires last.

Event bubbling

When you use event bubbling

               / \
---------------| |-----------------
| element1     | |                |
|   -----------| |-----------     |
|   |element2  | |          |     |
|   -------------------------     |
|        Event BUBBLING           |
-----------------------------------
the event handler of element2 fires first, the event handler of element1 fires last.

W3C model

W3C has very sensibly decided to take a middle position in this struggle. Any event taking place in the W3C event model is first captured until it reaches the target element and then bubbles up again.

                 | |  / \
-----------------| |--| |-----------------
| element1       | |  | |                |
|   -------------| |--| |-----------     |
|   |element2    \ /  | |          |     |
|   --------------------------------     |
|        W3C event model                 |
------------------------------------------
You, the web developer, can choose whether to register an event handler in the capturing or in the bubbling phase. This is done through the addEventListener() method explained on the Advanced models page. If its last argument is true the event handler is set for the capturing phase, if it is false the event handler is set for the bubbling phase.

Suppose you do

element1.addEventListener('click',doSomething2,true)
element2.addEventListener('click',doSomething,false)
If the user clicks on element2 the following happens:

The click event starts in the capturing phase. The event looks if any ancestor element of element2 has a onclick event handler for the capturing phase.
The event finds one on element1. doSomething2() is executed.
The event travels down to the target itself, no more event handlers for the capturing phase are found. The event moves to its bubbling phase and executes doSomething(), which is registered to element2 for the bubbling phase.
The event travels upwards again and checks if any ancestor element of the target has an event handler for the bubbling phase. This is not the case, so nothing happens.
The reverse would be

element1.addEventListener('click',doSomething2,false)
element2.addEventListener('click',doSomething,false)
Now if the user clicks on element2 the following happens:

The click event starts in the capturing phase. The event looks if any ancestor element of element2 has a onclick event handler for the capturing phase and doesn’t find any.
The event travels down to the target itself. The event moves to its bubbling phase and executes doSomething(), which is registered to element2 for the bubbling phase.
The event travels upwards again and checks if any ancestor element of the target has an event handler for the bubbling phase.
The event finds one on element1. Now doSomething2() is executed.
Compatibility with traditional model

In the browsers that support the W3C DOM, a traditional event registration

element1.onclick = doSomething2;
is seen as a registration in the bubbling phase.

Use of event bubbling

Few web developers consciously use event capturing or bubbling. In Web pages as they are made today, it is simply not necessary to let a bubbling event be handled by several different event handlers. Users might get confused by several things happening after one mouse click, and usually you want to keep your event handling scripts separated. When the user clicks on an element, something happens, when he clicks on another element, something else happens.

Of course this might change in the future, and it’s good to have models available that are forward compatible. But the main practical use of event capturing and bubbling today is the registration of default functions.

It always happens

What you first need to understand is that event capturing or bubbling always happens. If you define a general onclick event handler for your entire document

document.onclick = doSomething;
if (document.captureEvents) document.captureEvents(Event.CLICK);
any click event on any element in the document will eventually bubble up to the document and thus fire this general event handler. Only when a previous event handling script explicitly orders the event to stop bubbling, it will not propagate to the document.

Uses

Because any event ends up on the document, default event handlers become possible. Suppose you have this page:

------------------------------------
| document                         |
|   ---------------  ------------  |
|   | element1    |  | element2 |  |
|   ---------------  ------------  |
|                                  |
------------------------------------

element1.onclick = doSomething;
element2.onclick = doSomething;
document.onclick = defaultFunction;
Now if the user clicks on element1 or 2, doSomething() is executed. You can stop the event propagation here, if you wish. If you don’t the event bubbles up to defaultFunction(). If the user clicks anywhere else defaultFunction() is also executed. This might be useful sometimes.

Setting document–wide event handlers is necessary in drag–and–drop scripts. Typically a mousedown event on a layer selects this layer and makes it respond to the mousemove event. Though the mousedown is usually registered on the layer to avoid browser bugs, both other event handlers must be document–wide.

Remember the First Law of Browserology: anything can happen, and it usually does when you’re least prepared for it. So it may happen that the user moves his mouse very wildly and the script doesn’t keep up so that the mouse is not over the layer any more.

If the onmousemove event handler is registered to the layer, the layer doesn’t react to the mouse movement any more, causing confusion.
If the onmouseup event handler is registered on the layer, this event isn’t caught either so that the layer keeps reacting to the mouse movements even after the user thinks he dropped the layer. This causes even more confusion.
So in this case event bubbling is very useful because registering your event handlers on document level makes sure they’re always executed.

Turning it off

But usually you want to turn all capturing and bubbling off to keep functions from interfering with each other. Besides, if your document structure is very complex (lots of nested tables and such) you may save system resources by turning off bubbling. The browser has to go through every single ancestor element of the event target to see if it has an event handler. Even if none are found, the search still takes time.

In the Microsoft model you must set the event’s cancelBubble property to true.

window.event.cancelBubble = true
In the W3C model you must call the event’s stopPropagation() method.

e.stopPropagation()
This stops all propagation of the event in the bubbling phase. For a complete cross-browser experience do

function doSomething(e)
{
	if (!e) var e = window.event;
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
}
Setting the cancelBubble property in browsers that don’t support it doesn’t hurt. The browser shrugs and creates the property. Of course it doesn’t actually cancel the bubbling, but the assignment itself is safe.

currentTarget

As we’ve seen earlier, an event has a target or srcElement that contains a reference to the element the event happened on. In our example this is element2, since the user clicked on it.

It is very important to understand that during the capturing and bubbling phases (if any) this target does not change: it always remains a reference to element2.

But suppose we register these event handlers:

element1.onclick = doSomething;
element2.onclick = doSomething;
If the user clicks on element2 doSomething() is executed twice. But how do you know which HTML element is currently handling the event? target/srcElement don’t give a clue, they always refer to element2 since it is the original source of the event.

To solve this problem W3C has added the currentTarget property. It contains a reference to the HTML element the event is currently being handled by: exactly what we need. Unfortunately the Microsoft model doesn’t contain a similar property.

You can also use the this keyword. In the example above it refers to the HTML element the event is handled on, just like currentTarget.

Problems of the Microsoft model

But when you use the Microsoft event registration model the this keyword doesn’t refer to the HTML element. Combined with the lack of a currentTarget–like property in the Microsoft model, this means that if you do

element1.attachEvent('onclick',doSomething)
element2.attachEvent('onclick',doSomething)
you cannot know which HTML element currently handles the event. This is the most serious problem with the Microsoft event registration model and for me it’s reason enough never to use it, not even in IE/Win only applications.

I hope Microsoft will soon add a currentTarget–like property — or maybe even follow the standard? Web developers need this information.

Continue

If you wish to go through all event pages in order, you should now continue with the Mouse events page.
配置本地tomcat https tomcat https
配置本地Tomcat的https
(一)采用keytool生成证书
步骤:
1、	生成证书
keytool -genkey -alias tomcat -keyalg RSA -keystore d:\mykeystore -dname "CN=localhost, OU=localhost, O=localhost, L=SH, ST=SH, C=CN" -keypass changeit -storepass changeit
参数说明:
1)-genkey    创建一个新的密钥
2)-alias      密钥别名
3)-keyalg     加密算法,这里是RSA
4)-keystore   密钥保存的文件
5)-dname    表示密钥的distinguished names
              CN=commonName
              OU=oranizationUnit
              O = organizationName
              L=locatityName
              S=stateName
              C=country
6)-keypass    私有密钥的密码
7)-storepass   存取密码,用于从存储密钥的文件中(位于-keystore中指定的位置)将信息取出
2、	导出证书(说明:导出证书,由客户端安装)
keytool -export -alias tomcat -keystore d:\mykeystore -file d:\mycerts.cer -storepass changeit
参数说明:
1)-export    导出指定别名的证书到文件
2)-alias      密钥别名
3)-keystore    密钥保存的文件
4)-file         导出到指定的文件中
5)- storepass  密钥保存的文件的存储密码
3、	客户端配置(为客户端的JVM导入密钥(将服务器下发的证书导入到JVM中))
keytool -import -trustcacerts -alias tomcat -keystore "%JAVA_HOME%/jre/lib/security/cacerts" -file d:\mycerts.cer -storepass changeit
参数说明:
1)-import    将已签名数字证书导入密钥库
2)-trustcacerts 
3)-file       数字证书路径

验证是否成功导入到JVM证书库
keytool -list -alias tomcat -keystore "%JAVA_HOME%/jre/lib/security/cacerts " -storepass changeit
4、	其它命令
1、从jvm证书库中删除证书
keytool -delete -alias tomcat –keystore "%JAVA_HOME%/jre/lib/security/cacerts" -storepass changeit
2、从jvm证书库中导出证书
keytool -export -keystore "%JAVA_HOME%/jre/lib/security/cacerts" -storepass changeit -alias tomcat -file d:\ mycerts.cer

(二)配置Tomcat
1、注销server.xml中的语句:
<!--<Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />-->
否则tomcat会出现以下错误:
INFO: Initializing ProtocolHandler ["http-apr-8443"]
Jul 5, 2011 3:20:16 PM org.apache.coyote.AbstractProtocol init
SEVERE: Failed to initialize end point associated with ProtocolHandler ["http-apr-8443"]
java.lang.Exception: Connector attribute SSLCertificateFile must be defined when using SSL with APR
分析见:http://java.dzone.com/articles/ssl-your-tomcat-7

2、放开以下注释
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" 			   
			   keystoreFile="D:\mykeystore" keystorePass="changeit" />


mxgraph 三角形
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>mxTriangle</title>
        <script type="text/javascript">
            mxBasePath = '../src';
        </script>
        <!-- Loads and initializes the library -->
        <script type="text/javascript" src="http://www.diagram.ly/client?version=1.9.1.0"></script>
		<script type="text/javascript">
			function mxTriangle(){};
			mxTriangle.prototype = new mxActor();
			mxTriangle.prototype.constructor = mxTriangle;
			mxTriangle.prototype.redrawPath = function(path,x,y,w,h) {
				/*
                	path.moveTo(x,y+h);
					path.lineTo(x+w,y+h);
					path.lineTo((2*x+w)/2,y);
                */
				path.moveTo(0,h);
				path.lineTo(w,h);
				path.lineTo((w)/2,0);
				path.close();
				path.end();
			}
			mxCellRenderer.prototype.defaultShapes['mxTriangle'] = mxTriangle;
			
			function main(container)
			{
				if (!mxClient.isBrowserSupported()) {
					mxUtils.error('Browser is not supported!', 200, false);
				}
				else {
					root = new mxCell();
					var model = new mxGraphModel(root);
					var graph = new mxGraph(container,model);
					
					var style = new Object();
					style[mxConstants.STYLE_SHAPE] = 'mxTriangle';
					// Adds a gradient and shadow to improve the user experience
					style[mxConstants.STYLE_GRADIENTCOLOR] = '#FFFFFF';
					style[mxConstants.STYLE_SHADOW] = true;
					
					graph.getStylesheet().putCellStyle("mxtriangle",style);
					
					
					
					style = graph.getStylesheet().getDefaultEdgeStyle();
					style[mxConstants.STYLE_STROKECOLOR] = '#0C0C0C';
					style[mxConstants.STYLE_LABEL_BACKGROUNDCOLOR] = 'white';
					style[mxConstants.STYLE_EDGE] = mxEdgeStyle.ElbowConnector;
					style[mxConstants.STYLE_ROUNDED] = true;
					style[mxConstants.STYLE_FONTCOLOR] = 'black';
					style[mxConstants.STYLE_FONTSIZE] = '10';
					
					var layer0 = root.insert(new mxCell("hello world",mxGeometry(90,20,100,100),"mxtriangle"));
					var layer1 = root.insert(new mxCell()); 
					
					graph.setEnabled(true);
					
					
					//var vertex = new mxCell(null,new mxGeometry(0, 0, 60, 60), "shape=mxTriangle");
					var vertex1 = new mxCell(null,new mxGeometry(90, 20, 60, 60), "mxtriangle");
					var vertex2 = new mxCell(null,new mxGeometry(90, 20, 80, 80), "mxtriangle");
					vertex1.setVertex(true);		 //很关键,不然不会显示出来			
					vertex2.setVertex(true);					
					
					//var layer1 = new mxCell("hello world",mxGeometry(90,20,100,100),"shape=mxRectangleShape");
					layer0.setVertex(true);
					layer0.insert(vertex1,layer0.getChildCount());
					layer0.insert(vertex2,layer0.getChildCount());
					layer0.setCollapsed(false);
					//graph.addCell(layer1);
					
					//var parent = graph.getDefaultParent();
					graph.getModel().beginUpdate();
					try {
						 v1 = graph.insertVertex(layer1, null, 'Custom', 20, 20, 80, 60,"mxtriangle");
						var v2 = graph.insertVertex(layer1, null, 'Shape', 50, 50, 80, 60,"mxtriangle");
						var e1 = graph.insertEdge(layer1, null, '', v1, v2);
					}
					finally {
						window.console.log(model.isLayer(layer1));
						graph.getModel().endUpdate();
					}
				}
			}
		</script>
    </head>
    <body onload="main(document.getElementById('contain'))">
    	<div id="contain" style="position:absolute; top:10px; left:10px; width:400px; height:400px; border:1px solid #ddd;"></div>
    </body>
</html>
raphael
 Raphaël—JavaScript Library
 
Main Function
Raphael
Creates a canvas object(创建一个canvas画布) on which to draw. You must do this first, as all future calls to drawing methods from this instance will be bound to this canvas.
Parameters
1	container HTMLElement or string
2	width number
3	height number
or
4	x number
5	y number
6	width number
7	height number
or
8	all array (first 3 or 4 elements in the array are equal to [containerID, width, height] or [x, y, width, height]. The rest are element descriptions in format {type: type, <attributes>})
Usage
// Each of the following examples create a canvas that is 320px wide by 200px high
// Canvas is created at the viewport’s 10,50 coordinate
var paper =Raphael(10, 50, 320, 200);
// Canvas is created at the top left corner of the #notepad element
// (or its top right corner in dir="rtl" elements)
var paper =Raphael(document.getElementById("notepad"), 320, 200);
// Same as above
var paper =Raphael("notepad", 320, 200);
// Image dump
var set =Raphael(["notepad", 320, 200, {
    type: "rect",
    x: 10,
    y: 10,
    width: 25,
    height: 25,
    stroke: "#f00"
}, {
    type: "text",
    x: 30,
    y: 40,
    text: "Dump"
}]);
circle

Draws a circle.
Parameters
9	x number X coordinate of the centre
10	y number Y coordinate of the centre
11	r number radius
Usage
var c =paper.circle(50, 50, 40);
rect

Draws a rectangle.
Parameters
12	x number X coordinate of top left corner
13	y number Y coordinate of top left corner
14	width number
15	height number
16	r number [optional] radius for rounded corners, default is 0
Usage
// regular rectangle
var c =paper.rect(10, 10, 50, 50);
// rectangle with rounded corners
var c =paper.rect(40, 40, 50, 50, 10);
ellipse

Draws an ellipse.
Parameters
17	x number X coordinate of the centre
18	y number X coordinate of the centre
19	rx number Horisontal radius
20	ry number Vertical radius
Usage
var c =paper.ellipse(50, 50, 40, 20);
image

Embeds an image into the SVG/VML canvas.
Parameters
21	src string URI of the source image
22	x number X coordinate position
23	y number Y coordinate position
24	width number Width of the image
25	height number Height of the image
Usage
var c =paper.image("apple.png", 10, 10, 80, 80);
set

Creates array-like object to keep and operate couple of elements at once. Warning: it doesn’t create any elements for itself in the page.
Usage
var st =paper.set();
st.push(
    paper.circle(10, 10, 5),
    paper.circle(30, 10, 5)
);
st.attr({fill: "red"});
text
Raphaëlkicksbutt!
Draws a text string. If you need line breaks, put “\n” in the string.
Parameters
26	x number X coordinate position.
27	y number Y coordinate position.
28	text string The text string to draw.
Usage
var t =paper.text(50, 50, "Raphaël\nkicks\nbutt!");
path

Creates a path element by given path data string.
Parameters
29	pathString string [optional] Path data in SVG path string format.
Usage
var c =paper.path("M10 10L90 90");
// draw a diagonal line:
// move to 10,10, line to 90,90
clear
Clears the canvas, i.e. removes all the elements.
Usage
var c =paper.path("M10 10L90 90");
paper.clear();
Element’s generic methods
Each object created on the canvas shares these same generic methods:
node
Gives you a reference to the DOM object, so you can assign event handlers or just mess around.
Usage
// draw a circle at coordinate 10,10 with radius of 10
var c =paper.circle(10, 10, 10);
c.node.onclick =function () {
    c.attr("fill", "red");
};
paper
Internal reference to “paper” where object drawn. Mainly for use in plugins and element extensions.
Usage
Raphael.el.cross =function () {
    this.attr({fill: "red"});
    this.paper.path("M10,10L50,50M50,10L10,50")
        .attr({stroke: "red"});
}
remove
Removes element from the DOM. You can’t use it after this method call.
Usage
var c =paper.circle(10, 10, 10);
c.remove();
hide
Makes element invisible.
Usage
var c =paper.circle(10, 10, 10);
c.hide();
show
Makes element visible.
Usage
var c =paper.circle(10, 10, 10);
c.show();
rotate
Rotates the element by the given degree from its center point.
Parameters
30	degree number Degree of rotation (0 – 360°)
31	isAbsolute boolean [optional] Specifies is degree is relative to previous position (false) or is it absolute angle (true)
or
32	degree number Degree of rotation (0 – 360°)
33	cx number [optional] X coordinate of the origin of rotation
34	cY number [optional] Y coordinate of the origin of rotation
Usage
var c =paper.circle(10, 10, 10);
c.rotate(45);        // rotation is relative
c.rotate(45, true);  // rotation is absolute
translate
Moves the element around the canvas by the given distances.
Parameters
35	dx number Pixels of translation by X axis
36	dy number Pixels of translation by Y axis
Usage
var c =paper.circle(10, 10, 10);
// moves the circle 10 px to the right and down
c.translate(10, 10);
scale
Resizes the element by the given multiplier.
Parameters
37	Xtimes number Amount to scale horizontally
38	Ytimes number Amount to scale vertically
39	centerX number [optional] X of the center of scaling, default is the center of the element
40	centerY number [optional] Y of the center of scaling, default is the center of the element
Usage
var c =paper.circle(10, 10, 10);
// makes the circle 1.5 times larger
c.scale(1.5, 1.5);
// makes the circle half as wide, and 75% as high
c.scale(.5, .75);
attr
Sets the attributes of elements directly.
Parameters
41	attributeName string
42	value string
or
43	params object
or
44	attributeName string in this case method returns current value for given attribute name
or
45	attributeNames array in this case method returns array of current values for given attribute names
or
no parameters, in this case object containing all attributes will be returned
Possible parameters
Please refer to the SVG specification for an explanation of these parameters.
•	clip-rect string comma or space separated values: x, y, width and height
•	cursor string CSS type of the cursor
•	cx number
•	cy number
•	fill colour or gradient 
o	linear gradient: “‹angle›-‹colour›[-‹colour›[:‹offset›]]*-‹colour›”, example: “90-#fff-#000” – 90° gradient from white to black or “0-#fff-#f00:20-#000” – 0° gradient from white via red (at 20%) to black
o	radial gradient: “r[(‹fx›, ‹fy›)]‹colour›[-‹colour›[:‹offset›]]*-‹colour›”, example: “r#fff-#000” – gradient from white to black or “r(0.25, 0.75)#fff-#000” – gradient from white to black with focus point at 0.25, 0.75
o	Focus point coordinates are in 0..1 range
o	Radial gradients can only be applied to circles and ellipses
•	fill-opacity number
•	font string
•	font-family string
•	font-size number
•	font-weight string
•	height number
•	href string URL, if specified element behaves as hyperlink
•	opacity number
•	path pathString SVG path string format
•	r number
•	rotation number
•	rx number
•	ry number
•	scale string comma or space separated values: xtimes, ytimes, cx, cy. See: scale
•	src string (URL)
•	stroke colour
•	stroke-dasharray string [“”, “-”, “.”, “-.”, “-..”, “.”, “-”, “--”, “- .”, “--.”, “--..”]
•	stroke-linecap string [“butt”, “square”, “round”]
•	stroke-linejoin string [“bevel”, “round”, “miter”]
•	stroke-miterlimit number
•	stroke-opacity number
•	stroke-width number
•	target string used with href
•	text-anchor string [“start”, “middle”, “end”], default is “middle”
•	title string will create tooltip with a given text
•	translation string comma or space separated values: x and y
•	width number
•	x number
•	y number
Usage
var c =paper.circle(10, 10, 10);
// using strings
c.attr("fill", "black");
// using params object
c.attr({fill: "#000", stroke: "#f00", opacity: 0.5});
c.attr({
    fill: "90-#fff-#000",
    "stroke-dasharray": "-..",
    "clip-rect": "10, 10, 100, 100"
});
animate
Changes an attribute from its current value to its specified value in the given amount of milliseconds.
Parameters
46	newAttrs object A parameters object of the animation results. (Not all attributes can be animated.)
47	ms number The duration of the animation, given in milliseconds.
48	callback function [optional]
or
49	newAttrs object A parameters object of the animation results. (Not all attributes can be animated.)
50	ms number The duration of the animation, given in milliseconds.
51	easing string [“>”, “<”, “<>”, “backIn”, “backOut”, “bounce”, “elastic”, “cubic-bezier(p1, p2, p3, p4)”] or function [optional], see explanation re cubic-bezier syntax
52	callback function [optional]
or
53	keyFrames object Key-value map, where key represents keyframe timing: [“from”, “20%”, “to”, “35%”, etc] and value is the same as newAttrs from above, except it could also have easing and callback properties
54	ms number The duration of the animation, given in milliseconds.
Look at the example of keyframes usage
Attributes that can be animated
The newAttrs parameter accepts an object whose properties are the attributes to animate. However, not all attributes listed in the attr method reference can be animated. The following is a list of those properties that can be animated:
•	clip-rect string
•	cx number
•	cy number
•	fill colour
•	fill-opacity number
•	font-size number
•	height number
•	opacity number
•	path pathString
•	r number
•	rotation string
•	rx number
•	ry number
•	scale string
•	stroke colour
•	stroke-opacity number
•	stroke-width number
•	translation string
•	width number
•	x number
•	y number
Easing
For easing use built in functions or add your own by adding new functions to Raphael.easing_formulas object. Look at the example of easing usage.
Usage
var c =paper.circle(10, 10, 10);
c.animate({cx: 20, r: 20}, 2000);
c.animate({cx: 20, r: 20}, 2000, "bounce");
c.animate({
    "20%": {cx: 20, r: 20, easing: ">"},
    "50%": {cx: 70, r: 120, callback: function () {…}},
    "100%": {cx: 10, r: 10}
}, 2000);
Stop
Stops current animation.
Usage
var c =paper.circle(10, 10, 10);
c.animate({cx: 20, r: 20}, 2000);
// stop animation half way
setTimeout(function () { c.stop(); }, 1000);
animateWith
The same as animate method, but synchronise animation with another element.
Parameters
The same as for animate method, but first argument is an element.
Usage
var c =paper.circle(10, 10, 10),
    r =paper.rect(10, 10, 10, 10);
c.animate({cx: 20, r: 20}, 2000);
r.animateWith(c, {x: 20}, 2000);
animateAlong
Click here
Animates element along the given path. As an option it could rotate element along the path.
Parameters
55	path object or string path element or path string along which the element will be animated
56	ms number The duration of the animation, given in milliseconds.
57	rotate boolean [optional] if true, element will be rotated along the path
58	callback function [optional]
Usage
var p =r.path("M100,100c0,50 100-50 100,0c0,50 -100-50 -100,0z").attr({stroke: "#ddd"}),
    e =r.ellipse(104, 100, 4, 4).attr({stroke: "none", fill: "#f00"}),
    b =r.rect(0, 0, 620, 400).attr({stroke: "none", fill: "#000", opacity: 0}).click(function () {
        e.attr({rx: 5, ry: 3}).animateAlong(p, 4000, true, function () {
            e.attr({rx: 4, ry: 4});
        });
    });
animateAlongBack
Similar to animateAlong. Animates element along the given path, starting from the end of it.
onAnimation
Click here
Sets or resets the function that will be called on each stage of the animation.
Parameters
59	f function function that will be called on each stage of animation
Usage
var p =r.path("M10,50c0,50,80-50,80,0c0,50-80-50-80,0z"),
    p2 =r.path(),
    e =r.ellipse(10, 50, 4, 4).attr({stroke: "none", fill: "#f00"}).onAnimation(function () {
        p2.attr({path: "M50,10L" +e.attr("cx") +"," +e.attr("cy")});
    }),
    b =r.rect(0, 0, 620, 400).attr({stroke: "none", fill: "#000", opacity: 0}).click(function () {
        e.attr({rx: 5, ry: 3}).animateAlong(p, 4000, true, function () {
            e.attr({rx: 4, ry: 4});
        });
    });
getBBox
Returns the dimensions of an element.
Usage
var c =paper.circle(10, 10, 10);
var width =c.getBBox().width;
toFront
Moves the element so it is the closest to the viewer’s eyes, on top of other elements.
Usage
var c =paper.circle(10, 10, 10);
c.toFront();
toBack
Moves the element so it is the furthest from the viewer’s eyes, behind other elements.
Usage
var c =paper.circle(10, 10, 10);
c.toBack();
insertBefore
Inserts current object before the given one.
Usage
var r =paper.rect(10, 10, 10, 10);
var c =paper.circle(10, 10, 10);
c.insertBefore(r);
insertAfter
Inserts current object after the given one.
Usage
var r =paper.rect(10, 10, 10, 10);
var c =paper.circle(10, 10, 10);
r.insertAfter(c);
clone
Returns a clone of the current element.
Usage
var r =paper.rect(10, 10, 10, 10);
var c =r.clone();
Graphic Primitives
Methods of “paper” object, created with Raphael function call.
raphael
Internal reference to Raphael object. In case it is not available.
Usage
Raphael.el.red =function () {
    var hsb =this.paper.raphael.rgb2hsb(this.attr("fill"));
    hsb.h =1;
    this.attr({fill: this.paper.raphael.hsb2rgb(hsb).hex});
}
getTotalLength
Path specific method. Returns length of the path in pixels.
Usage
var p =r.path("M100,100c0,50 100-50 100,0c0,50 -100-50 -100,0z");
    alert(p.getTotalLength());
getPointAtLength

Path specific method. Returns point description at given length.
Parameters
60	length number length in pixels from the beginining of the path to the point
Usage
var p =r.path("M10,50c0,50,80-50,80,0c0,50-80-50-80,0z");
    var point =p.getPointAtLength(30);
    r.circle(point.x, point.y, 3);
Returned object format:
•	x – x coordinate of the point
•	y – y coordinate of the point
•	alpha – angle of the path at the point
getSubpath

Path specific method. Returns the subpath string of a given path.
Parameters
61	from number length in pixels from the beginning of the path to the beginning of the subpath
62	to number length in pixels from the beginning of the path to the end of the subpath
Usage
var p =r.path("M10,50c0,50,80-50,80,0c0,50-80-50-80,0z");
    var path =p.getSubpath(10, 60);
    r.path(path).attr({stroke: "#f00"});
setSize
If you need to change dimensions of the canvas call this method
Parameters
63	width number new width of the canvas
64	height number new height of the canvas
setWindow
Should be called before main Raphael method. Sets which window should be used for drawing. Default is the current one. You need to use it if you want to draw inside iframe
Parameters
65	window object
getRGB
Parses passes string and returns an colour object. Especially useful for plug-in developers.
Parameters
66	color string Colour in form acceptable by library
Usage
var stroke =Raphael.getRGB(circle.attr("stroke")).hex;
angle
Gives you an angle of the line formed by two points or angle between two lines formed by three points.
Parameters
67	x1 number X of the first point
68	y1 number Y of the first point
69	x2 number X of the second point
70	y2 number Y of the second point
71	x3 number X of the third point [optional]
72	y3 number Y of the third point [optional]
Usage
var angle =Raphael.angle(10, 10, 50, 50);
rad
Converts angle to radians.
Parameters
73	deg number value of an angle in degrees
Usage
var Sin =Math.sin(Raphael.rad(45));
deg
Converts angle to degree.
Parameters
74	rad number value of an angle in radians
snapTo
Returns a number adjusted to one of various values, if it’s close enough.
Parameters
75	values number or array If values is a number, the value will be snapped to any multiple. If an array, the value will be snapped to the first element that’s within tolerance.
76	value number The value to adjust
77	tolerance number The value must be within tolerance of one of the snap values, or it will be returned unchanged [optional, default 10]
Usage
// adjust -10..10 to 0, 40..60 to 50, 90-110 to 100, etc
x =Raphael.snapTo(50, x);
// adjust 5..35 to 20, 45..75 to 60, otherwise no change
x =Raphael.snapTo([20, 60], x, 15);
getColor
Returns a colour object for the next colour in spectrum
Parameters
78	value number brightness [optional]
Usage
var c =paper.path("M10,10L100,100").attr({stroke: Raphael.getColor()});
getColor.reset
Resets getColor function, so it will start from the beginning
registerFont
Adds given font to the registered set of fonts for Raphaël. Should be used as an internal call from within Cufón’s font file. More about Cufón and how to convert your font form TTF, OTF, etc to JavaScript file. Returns original parameter, so it could be used with chaining.
Parameters
79	font object the font to register
Usage
Cufon.registerFont(Raphael.registerFont({…}))
getFont
Finds font object in the registered fonts by given parameters. You could specify only one word from the font name, like “Myriad” for “Myriad Pro”.
Parameters
80	family string font family name or any word from it
81	weight string weight of the font [optional]
82	style string style of the font [optional]
83	stretch string stretch of the font [optional]
Usage
paper.print(100, 100, "Test string", paper.getFont("Times", 800), 30);
print

Creates set of shapes to represent given font at given position with given size. Result of the method is set object (see set) which contains each letter as separate path object.
Parameters
84	x number x position of the text
85	y number y position of the text
86	text string text to print
87	font object font object (see getFont)
88	font_size number size of the font
Usage
var txt =r.print(10, 50, "print", r.getFont("Museo"), 30).attr({fill: "#fff"});
// following line will paint first letter in red
txt[0].attr({fill: "#f00"});
Adding your own methods to canvas
You can add your own method to the canvas. For example if you want to draw pie chart, you can create your own pie chart function and ship it as a Raphaël plugin. To do this you need to extend Raphael.fn object. Please note that you can create your own namespaces inside fn object. Methods will be run in context of canvas anyway. You should alter fn object before Raphaël instance was created, otherwise it will take no effect.
Usage
Raphael.fn.arrow =function (x1, y1, x2, y2, size) {
    return this.path( ... );
};
// or create namespace
Raphael.fn.mystuff ={
    arrow: function () {…},
    star: function () {…},
    // etc…
};
var paper =Raphael(10, 10, 630, 480);
// then use it
paper.arrow(10, 10, 30, 30, 5).attr({fill: "#f00"});
paper.mystuff.arrow();
paper.mystuff.star();

Adding your own methods to elements
You can add your own method to elements. This is usefull when you want to hack default functionality or want to wrap some common transformation or attributes in one method. In difference to canvas mathods, you can redefine element method at any time.
Usage
Raphael.el.red =function () {
    this.attr({fill: "#f00"});
};
// then use it
paper.circle(100, 100, 20).red();

Custom Attributes
If you have a set of attributes that you would like to represent as a function of some number you can do it easily with custom attributes:
Usage
paper.customAttributes.hue =function (num) {
    num =num % 1;
    return {fill: "hsb(" +num +", .75, 1)"};
};
// Custom attribute “hue” will change fill
// to be given hue with fixed saturation and brightness.
// Now you can use it like this:
var c =paper.circle(10, 10, 10).attr({hue: .45});
// or even like this:
c.animate({hue: 1}, 1e3);

// You could also create custom attribute
// with multiple parameters:
paper.customAttributes.hsb =function (h, s, b) {
    return {fill: "hsb(" +[h, s, b].join(",") +")"};
};
c.attr({hsb: ".5 .8 1"});
c.animate({hsb: "1 0 .5"}, 1e3);

Supported colour formats
You could specify colour in this formats:
•	Colour name (“red”, “green”, “cornflowerblue”, etc)
•	#••• — shortened HTML colour: (“#000”, “#fc0”, etc)
•	#•••••• — full length HTML colour: (“#000000”, “#bd2300”)
•	rgb(•••, •••, •••) — red, green and blue channels’ values: (“rgb(200, 100, 0)”)
•	rgb(•••%, •••%, •••%) — same as above, but in %: (“rgb(100%, 175%, 0%)”)
•	rgba(•••, •••, •••, •••) — red, green and blue channels’ values: (“rgba(200, 100, 0, .5)”)
•	rgba(•••%, •••%, •••%, •••%) — same as above, but in %: (“rgba(100%, 175%, 0%, 50%)”)
•	hsb(•••, •••, •••) — hue, saturation and brightness values: (“hsb(0.5, 0.25, 1)”)
•	hsb(•••%, •••%, •••%) — same as above, but in %
•	hsba(•••, •••, •••, •••) — same as above, but with opacity
•	hsl(•••, •••, •••) — almost the same as hsb, see Wikipedia page
•	hsl(•••%, •••%, •••%) — same as above, but in %
•	hsla(•••, •••, •••) — same as above, but with opacity
•	Optionally for hsb and hsl you could specify hue as a degree: “hsl(240deg, 1, .5)” or, if you want to go fancy, “hsl(240°, 1, .5)”
Usage
paper.circle(100, 100, 20).attr({
    fill: "hsb(0.6, 1, 0.75)",
    stroke: "red"
});
safari
There is an inconvenient rendering bug is Safari (WebKit): sometimes the rendering should be forced. This method should help with dealing with this bug.
Usage
paper.safari();
“Ninja Mode”
If you want to leave no trace of Raphaël (Well, Raphaël creates only one global variable Raphael, but anyway.) You can use ninja method. Beware, that in this case plugins could stop working, because they are depending on global variable existance.
Usage
(function (local_raphael) {
    var paper =local_raphael(10, 10, 320, 200);
    …
})(Raphael.ninja());

Events
You can attach events to elements by using element.node and your favourite library ($(circle.node).click(…)) or you can use built-in methods:
Usage
element.click(function (event) {
    this.attr({fill: "red"});
});
element.dblclick(function (event) {
    this.attr({fill: "red"});
});
element.mousedown(function (event) {
    this.attr({fill: "red"});
});
element.mousemove(function (event) {
    this.attr({fill: "red"});
});
element.mouseout(function (event) {
    this.attr({fill: "red"});
});
element.mouseover(function (event) {
    this.attr({fill: "red"});
});
element.mouseup(function (event) {
    this.attr({fill: "red"});
});
element.hover(function (event) {
    this.attr({fill: "red"});
}, function (event) {
    this.attr({fill: "black"});
}, overScope, outScope);
Second parameter is optional scope. By default handlers are run in the scope of the element. To unbind events use the same method names with “un” prefix, i.e. element.unclick(f);
Drag ’n’ Drop
To make element “draggable” you need to call method drag on element.
Parameters
89	onmove function event handler for moving
90	onstart function event handler for start
91	onend function event handler for end of the drag
Usage
var c =R.circle(100, 100, 50).attr({
    fill: "hsb(.8, 1, 1)",
    stroke: "none",
    opacity: .5
});
var start =function () {
    // storing original coordinates
    this.ox =this.attr("cx");
    this.oy =this.attr("cy");
    this.attr({opacity: 1});
},
move =function (dx, dy) {
    // move will be called with dx and dy
    this.attr({cx: this.ox +dx, cy: this.oy +dy});
},
up =function () {
    // restoring state
    this.attr({opacity: .5});
};
c.drag(move, start, up);
To unbind drag use the undrag method.
Home
Contents
•	Raphael
•	circle
•	rect
•	ellipse
•	image
•	set
•	text
•	path
•	clear
•	node
•	paper
•	remove
•	hide
•	show
•	rotate
•	translate
•	scale
•	attr
•	animate
•	stop
•	animateWith
•	animateAlong
•	animateAlongBack
•	getBBox
•	toFront
•	toBack
•	insertBefore
•	insertAfter
•	clone
•	raphael
•	getTotalLength
•	getPointAtLength
•	getSubpath
•	setSize
•	setWindow
•	getRGB
•	angle
•	rad
•	deg
•	snapTo
•	getColor
•	getColor.reset
•	registerFont
•	getFont
•	print
•	Adding your own methods to canvas
•	Adding your own methods to elements
•	Custom Attributes
•	Supported colour formats
•	safari
•	“Ninja Mode”
•	Events
Some Rights Reserved by Dmitry Baranovskiy
Logo by Wasabicube

学习网站:
http://net.tutsplus.com/tutorials/javascript-ajax/an-introduction-to-the-raphael-js-library/
svg  path:
http://www.chinasvg.com/support/svg-tutorial/svg-path-directive-guide.html
raphael
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
		<title>Untitled Document</title>
		<script type="text/javascript" src="../raphael.js"></script>
	</head>
	<body>
		<script type="text/javascript">
			window.onload = function() {
				var paper = Raphael(20,30, 100, 300);
				var c = paper.circle(50,50,40);
				
				//创建一个新的画布
				var paper = Raphael("canvas", 640, 480);
        		
				//画圆
				var c = paper.circle(10, 10, 10).attr({fill: "#a9ea00", stroke: "none"}).animate({cx:100,cy:100,r: 20}, 2000)
				
				//画线
				var path =  paper.path("M250 150 L150 350 L350 350 Z");
				
				var path =  paper.path("M250 150 H400 L450 180");
			}
		</script>
		<div id="holder"></div>
		<div id="canvas"></div>
	</body>
</html>
Global site tag (gtag.js) - Google Analytics