Search

10/31/2007

keyCode and keyEvent: onkeydown onkeypress onkeyup

要利用鍵盤來進行操作,首先要先在document bind一個key event,key event(至少)有三個,keydown, keypress, keyup,測試一下這些key event能否抓到正確的key code,測試的script如下

<body>
empty document
</body>
<script>
document.onkeyup = function(e){
if(!e) e = window.event;
alert(e.keyCode)'
}

keyup: IE OK, FF: OK
keydown: IE OK, FF: OK
keypress; IE: 英文數字OK, 方向鍵not OK FF: not OK

另外keydown可以在使用者一直按著某個鍵時,持續的產生event,如果想做一個一直按著某個鍵,重複一些動作,keydown會是很好的人選。
ex: http://chunghe.googlepages.com/keycode-and-keyevent-onkeydown.htm
在這個例子中,持續按著就會一直產生key event,不需要setInterval之類的咚咚

10/29/2007

Abbreviation vs. Acronym

Oxford English Dictionary


  • Abbreviation: A shortened form of a word or phrase.

  • Acronym: A word formed from the initial letters of other words (e.g., laser, which is an acronym of Light Amplification by Stimulated Emissio of Radiation).

  • Initialism: An abbreviation consisting of initial letters pronounced separately(e.g., BBC).

all acronyms and initialisms are abbreviations, but not all abbreviations are acronyms or initialisms.

10/28/2007

div的高度

遇到一個問題,一個空的DIV,高度會是多少?

<div style="width:150px; background-color:red;"></div>
IE: 高度19px
FF: 0

如果強制設定高度為0px,高度會是多少?這個就有趣了
<div style="width:150px; height:0px; background-color"></div>
IE: 高度19px
FF:0

可能是字型的原因,把字型設為0px看看
<div style="width:150px; height:0px; font-size: 0px; background-color"></div>
IE: 高度2px
FF:0

看起來是有點效果,但是要如何才能讓他高度為0? IE div height problem
1) Put a comment inside the div:  <div style="height: 10px;"><!-- --></div>
2) Put a &nbsp; inside the div and add this to its style: font-size:1px;
line-height:0.

第一招蠻神奇的,只要不設定height,就不會顯示出該div,both work in IE && FF
在有內文的情形下,就用第二招吧
<div style=" width: 150px;  font-size:1px; line-height:0; background-color: red ">foo</div>

10/20/2007

如何使用z-index蓋住flash

Tsung's Blog | CSS: 讓圖片蓋在 Flash Player 上面(使用 z-index) - 最近遇到一個一模一樣的問題, 一個z-index比較大的 element 蓋不住 flash, 解法是設定為 wmode="opaque"


  • wmode = "window" , default, flash player在最上層
  • wmode = "opaque" , flash player 介於 element 與 element的背景中間
  • wmode = "transparent", flash player 位於 element 的背景下方
針對 <object>/<embed> 的設法:
* 於 <object> 內加 <param name="wmode" value="transparent">, ex: <object>.... <param name="wmode" value="transparent"> ...</object>
* 於 <embed> 內加 wmode="transparent" 參數, ex: <embed wmode="transparent" ....>

針對 AC_RunActiveContent.js 的設法:

* 於 AC_FL_RunContent() 多加 'wmode', 'transparent' 的參數, ex: AC_FL_RunContent(.... 'wmode', 'transparent' ...);
* <noscript> 內, 應該最好也要加如上述 <object>/<embed> 的參數.

javascript idiom: getComputedStyle + currentStyle

The first argument to this method is the element whose computed style is desired. The second argument is any CSS pseudoelement, such as ":before" or ":after" whose style is desired. You probably won't be interested in a pseudoelement, but in the Mozilla and Firefox implementation of this method, the second argument is required and may not be omitted.

var p = document.getElementsByTagName("p")[0]; // Get first paragraph of doc
var typeface = ""; // We want its typeface
if (p.currentStyle) // Try simple IE API first
typeface = p.currentStyle.fontFamily;
else if (window.getComputedStyle) // Otherwise use W3C API
typeface = window.getComputedStyle(p, null).fontFamily;

Computed styles are quirky, and querying them does not always provide the information you want. Consider the typeface example just shown. The CSS font-family attribute accepts a comma-separated list of desired font families for cross-platform portability. When you query the fontFamily attribute of a computed style, you're simply getting the value of the most specific font-family style that applies to the element. This may return a value such as "arial,helvetica,sans-serif", which does not tell you which typeface is actually in use. Similarly, if an element is not absolutely positioned, attempting to query its position and size through the top and left properties of its computed style often returns the value "auto". This is a perfectly legal CSS value, but it is probably not what you were looking for.

update:
  1. YUI的 YAHOO.util.Dom.getStyle(el, 'fontFamily') 的傳回值仍然是整組的css property.( ex: arial, verdana, sans-serif);
  2. 以下的例子是使用抓取 pseudoelement 'hover' 的方法
    console.log( window.getComputedStyle($('link'), 'hover').color );
    <a id="link" href="#">l;www.foo.bar</a>
    傳回值: rgb(0, 0, 238),明顯是錯誤的答案。(rgb(0, 0, 238)是FF預設的a:link color)
    Re: How is the hover pseudo-class translated into the DOM? from Bjoern Hoehrmann on 2007-03-26 (www-dom@w3.org from January to March 2007)
    Ok, here's the tricky part, according to this article, the only way to get the hover color is to fire getComputedColor() while hovering it. You can't set the second parameter to hover 'cause it's not a psudo-element, it's only a matching condition. Here's the example
    window.onload = function(){
    $('link').onmouseover = function(){
    console.log( window.getComputedStyle($('link'), null).color );
    }
    }
    the return value will be rgb(255, 0, 0) which is correct.

10/17/2007

YUI code snippets

Photo Batching | ThinkVitamin.com
Skinning JS solutions - CSS JavaScript friction and fusion - 這種寫法的好處是
1. 使用者reload不會總是回到第一個tab: 技巧是toc裡面的<a href>帶有#號,自然location.href裡面就有#號,然後在某個tab做reload的話,可以判斷使用者原本在的tab,不會每次都回到第一個tab。
2. click event是 bind 在 toc 裡面,再由 YAHOO.util.event.getTarget(e)去抓取實際點取到的 tab,不需要每個 tab 都 bind 一個 click listener
3. 最後 return pub,只有pub是pub.init是pulic method,其餘的getBookmark, show都是private method


<ul id="toc">
<li><a href="#spec1">Spec 1</a></li>
<li><a href="#spec2">Spec 2</a></li>
<li><a href="#spec3">Spec 3</a></li>
<li><a href="#spec4">Spec 4</a></li>
<li><a href="#spec5">Spec 5</a></li>
</ul>

YAHOO.example.tocnav = function(){
var pub = {};
function show(e){
var t = YAHOO.util.Event.getTarget(e);
if(t.nodeName.toLowerCase()==='a'){
if(pub.current){
YAHOO.util.Dom.removeClass(pub.current,'show');
}
var target = YAHOO.util.Dom.get(t.href.split('#')[1]);
if(target){
pub.current = target.parentNode;
YAHOO.util.Dom.addClass(pub.current,'show');
}
}
};
function getBookmark(){
var bookmark = window.location.hash.replace('#','');
var t = YAHOO.util.Dom.get(bookmark);
return t ? t.parentNode : false;
};
pub.init = function(){
pub.current = getBookmark();
YAHOO.util.Dom.addClass(this,'js');
YAHOO.util.Dom.addClass(pub.current,'show');
YAHOO.util.Event.addListener('toc','click',show);
};
return pub;
}();
YAHOO.util.Event.onAvailable('faq',YAHOO.example.tocnav.init);

Reading out element dimensions with YUI Region
ver Y = YAHOO.util;
var $D = Y.Dom;
var $E = Y.Event;
var $ = $D.get;


YAHOO.util.Dom.setStyle(['test', 'test2'], 'opacity', 0.5);
var opacity = YAHOO.util.Dom.getStyle('test2', 'opacity');


/* return 放 public method, 其他private放在return之前 */
YAHOO.MyProperty = function () {
var privateVariable;
function privateFunction(x) {
...privateVariable...
}
return {
firstMethod: function (a, b) {
...privateVariable...
},
secondMethod: function (c) {
...privateFunction()...
}
};
}();

1. onAvailable 裡面可以用 this,這邊指的是 'yui-main',用在getElementsByClassName的第三個參數可以限定只在 'yui-main' 裡面找
2. getRegion 可以取得 block 的上下邊的 y 軸座標以及左右邊的 x 軸座標, ex:
var region = YAHOO.util.Dom.getRegion ( YAHOO.util.Dom.get('test') );
回傳 Region {top: 32, right: 825, bottom: 1334, left: 173}
可用region.top / region.bottom 取得 border-top / border-bottom 的 y 軸座標
region.left / region.right 取得 border-left / border-right 的 x 軸座標

另外也可以用getXY取得左上角的座標, ex:
var region = YAHOO.util.Dom.getXY ( YAHOO.util.Dom.get('test') );

回傳 [173, 32] 分別對應到上一個 region.left region.top, 也就是該element的
左上角的[x軸, y軸] 座標
3. height = reg.bottom - reg.top; 可以決定 div 的高度。

YAHOO.util.Event.onAvailable('yui-main',function(){
var reg = YAHOO.util.Dom.getRegion(this.getElementsByTagName('div')[0]);
var height = reg.bottom - reg.top;
var grids = YAHOO.util.Dom.getElementsByClassName('yui-u','div',this);
for(var i=0;grids[i];i++){
YAHOO.util.Dom.setStyle(grids[i],'height',height+'px');
};
});

YAHOO.util.Dom.getDocumentHeight(); // 取得整個document的高
YAHOO.util.Dom.getDocumentWidth();
YAHOO.util.Dom.getViewportHeight()); // 取得可視範圍的高
YAHOO.util.Dom.getViewportWidth());

1. 示範namespace的用法, 預設的namespace定義在YAHOO global object, 只有YAHOO.util YAHOO.example, YAHOO.widget
2. $E.on的是$E.addListener的alias, 第一個參數可以傳一個id的array, 函數中的this同樣是指到 apply 的 element, 這邊是 $('test1') or $('test2')
3. 通過 setStyle(el, 'opacity', '0.7') 可以快速的設定opacity, 最後一個參數是 follow standard 0-1之間的opacity
4. 利用return 來區別private & public, 整各YAHOO.foo.bar.example是一個函式, 外界無法更動裡面的職, data hiding.

YAHOO.namespace('foo.bar');
var y = YAHOO.util;
var $E = y.Event;
var $D = y.Dom;
var $ = $D.get;
var $$ = $D.getElementsBy;

YAHOO.foo.bar.example = function(){
return {
init: function(){
$E.on(['test1', 'test2'], 'click', function(){
$D.setStyle(this, 'backgroundColor','red');
$D.setStyle(this, 'opacity', '0.7');
})
}
}
}()
$E.onDOMReady(YAHOO.foo.bar.example.init);

10/16/2007

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet - 太常看到這串字了,特別查了一下,沒想到歷史這麼悠久,還有Firefox addon: Dummy Lipsum,有趣。

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

另外還有各種不同的假文產生器:
亂數假文產生器 - Chinese Lorem Ipsum
Lorem ipsum 以外的新選擇 ¶ Lvx ex Cælis

z-index

Relatively Absolute @ The Autistic Cuckoo
1. 在position: absolute下,除了IE以外,皆可以藉由同時指定top left bottom right由瀏覽器算出block的長跟寬。
2. 有關 z-index,我一直以為是直接設定element的z-index,應該是要設定containing block的z-index,文末指出的例子值得好好想一想,改天再來做個實驗。

When positioned elements overlap, we can control the stacking order with the
z-index property. The higher the z-index, the closer
to the user the element ends up. Unfortunately this isn't quite as
straightforward as it sounds, since each containing block establishes its own
context for z-index. So to put one element on top of another
element, with a different containing block, you need to increase the
z-index for the first element's containing block. In
really complex layouts you can find yourself in impossible situations, if you
want to stack three elements where the middle one has a different containing
block than the other two. As far as we know, this cannot be done.


update:
CSS Z-index Property
Note: Z-index only works on elements that have been positioned (eg position:absolute;)!

Always Show Vertical Scrollbar in Firefox [firefox] [css] [web]

Always Show Vertical Scrollbar in Firefox [firefox] [css] [web] - 為什麼要always show vertical scrollbar in Firefox?在IE中,vertical scroll bar 會一直在,不管content的長短,這反而解決了一個問題:在一個置中的欄位中,如果內容太長,Firefox會出現 scrollbar並且佔掉部分的document width,導致置中的欄位移動,畫面不美觀,目前沒有太好的解決辦法,先讓FF的scrollbar一直在吧。

/* always show scrollbar in FF  */
html {
overflow: -moz-scrollbars-vertical;
}
/* hide necessary scrollbar for textarea in IE */

* html textarea{
overflow:auto;
}

update: there's a side effect: horizontal scrollbars will never appear
* -moz-scrollbars-horizontal: Indicates that horizontal scrollbars should always appear and vertical scrollbars should never appear.
* -moz-scrollbars-vertical: Indicates that vertical scrollbars should always appear and horizontal scrollbars should never appear.
* -moz-scrollbars-none: Indicates that no scrollbars should appear but the element should be scrollable from script. (This is the same as hidden, and has been since Mozilla 1.6alpha.)

Forcing Firefox to always show a scroll bar - TOLRA Community Forums
Adding the following to your CSS file causes Firefox to always show the scroll bar:
Code:

html { min-height: 100%; margin-bottom: 1px; }

The normal operation is for Firefox to remove the scroll bar if it's not needed which can lead to the page shifting left and right slightly between long and short pages.

update: this is one perfect solution
Always Show Vertical Scrollbar in Firefox [firefox] [css] [web]
html {overflow: scroll;} works but it also gives you a horizontal scroll bar.
html {overflow-y: scroll;} will give you just a vertical scroll bar, if that's what you are going for.

10/15/2007

IE/win Expanding Box

IE/win Expanding Box - 這篇討論一個IE的bug,對於一個fixed width的DIV container,裡面的content 如果比 container 還要長的話,guess what? IE會把fixed width的 container 稱大來match 裡面的 content,genius!
W3C standard 規定 overflow 的 default 是 visible,就是過長的內容會跑到 container 外面,可能會蓋到外面的內容。
這個 bug 沒有解法,只有workaround,也就是用word-wrap: break-word;把過長的行斷掉,注意這是 IE only 的 property。所以

<!--[if IE]>
<style type="text/css">
body {word-wrap: break-word;}
</style>
<![endif]-->


另一個作法是overflow:hidden,
Another drawback of the "hidden" method is that IE/win demands that the boxes having this overflow fix must have widths applied to them. So for example, consider a nested paragraph in one of those floated columns above. The floats do have widths but the nested paragraph will normally be left widthless. If the overflow: hidden; trick is used on the paragraph, it will fail in IE/Win. But, if it's used on the surrounding float it will then work properly, because the element with the overflow rule also has a width applied to it.

In summary, both word-wrap: break-word and overflow: hidden are possible workarounds that will make Internet Explorer respect our specified dimensions. The method of overflow: hidden works in more situations -- such as oversized images and vertical expansions, but at the cost of possibly clipped content. The word-wrap: break-word; method won't clip content, but is useless on anything but text. Now that you have seen the effects of both, their possible employment will depend on specific situations and preferences.

10/13/2007

只要加一行,讓 IE 五倍速執行 JavaScript ¶ Lvx ex Cælis

只要加一行,讓 IE 五倍速執行 JavaScript ¶ Lvx ex Cælis - 之前不知道在那邊有看到,不明白他的道理,anyway,這一篇解釋的很清楚。

/*@cc_on _d=document;eval('var document=_d')@*/


/*@cc_on
eval((function(props) {
var code = [];
for (var i = 0 l = props.length;i<l;i++){
var prop = props[i];
window['_'+prop]=window[prop];
code.push(prop+'=_'+prop)
}
return 'var '+code.join(',');
})('document self top parent alert setInterval clearInterval setTimeout clearTimeout'.split(' ')));
@*/

link 的四種狀態

Q: a 跟 a:link的權重誰比較高?
A: a:link比較高
a /* specificity = 1 */
a:link /* specificity = 1,1 */

Q: a:link a:hover a:active a:visited 誰的權重比較高?
A: 都一樣高
a:link /* specificity = 1,1 */
a:hover /* specificity = 1,1 */
a:active /* specificity = 1,1 */
a:visited /* specificity = 1,1 */

Q: a:link 與 a:visited 有何不同?
A: a:link 指的是 unvisited link, a:visited 指的是 visited link,注意皆必須有 href 的屬性(a name="foobar" 不會apply這些屬性)。
比較詳細的定義如下

:link
Refers to any anchor that is a hyperlink (i.e., has an href attribute) and points to an address that has not been visited. Note that some browsers may incorrectly interpret :link to refer to any hyperlink, visited or unvisited.
:visited
Refers to any anchor that is a hyperlink to an already visited address.


Q: a{color:red} 與 a:link{color:red} 有何不同?
A: a{color:red}不僅 apply 到 <a href="foobar"> ,也會apply到 < a name="section4"> ,而 a:link{color:red} 只會apply到前者。

Q: 我有聽過 :link :visited :hover :active(LoVe HAte) 的順序,有什麼意義嗎?
A: 主要是因為這些 pseudo class有相同的權重,所以這個順序是依照一般事件發生的順序排列的,一般是一個 link,然後會 hover 過去,最後才是點擊發生的 active。假設今天順序寫成 a:hover{color:red} a:link, a:visited{color:blue},當滑鼠移過去 link 的時候,這時候連結仍然會是藍色的,因為 a:hover 的屬性會被 a:link 或 a:visited 蓋過去。

另外,由於:link與:visited不會同時出現(要不是visited就是unvisited),這個順序也可以換成:visited :link :hover :active,不過就沒有口訣了。

Reference: Eric Meyer: Link Specificity

JavaScript Empty link - JumbaWiki

JavaScript Empty link - JumbaWiki

<a href="javascript:;">Do nothing</a>
<a href="javascript:void(0);">Do nothing</a>

10/09/2007

don't use new in Javascript

JavaScript, We Hardly new Ya » Yahoo! User Interface Blog

You never need to use new Object() in JavaScript. Use the object literal {} instead. Similarly, don’t use new Array(), use the array literal [] instead. Arrays in JavaScript work nothing like the arrays in Java, and use of the Java-like syntax will confuse you.

Do not use new Number, new String, or new Boolean. These forms produce unnecessary object wrappers. Just use simple literals instead.

So the rule is simple: The only time we should use the new operator is to invoke a pseudoclassical Constructor function. When calling a Constructor function, the use of new is mandatory.

10/04/2007

Javascript: substring, substr

Tsung's Blog | JavaScript: substr() 負數的算法 IE, Firefox 不同

語法 string.substring(from, to)
  • from: A nonnegative integer that specifies the position within string of the first character of the desired substring.
  • the length of the returned substring is always equal to to-from.
  • String.slice( ) and the nonstandard String.substr( ) can also extract substrings from a string. Unlike those methods, String.substring( ) does not accept negative arguments.

語法 string.substr(start, length)
  • from: If this argument is negative, it specifies a position measured from the end of the string: -1 specifies the last character, -2 specifies the second-to-last character, and so on.
  • Negative values for start do not work in IE 4 (this is fixed in later versions of IE). Instead of specifying a character position measured from the end of the string, they specify character position 0.




https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/Slice

語法 array.slice: The slice() method selects a part of an array, and returns the new array. Note: The original array will not be changed.
* For object references (and not the actual object), slice copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.

* For strings and numbers (not String and Number objects), slice copies strings and numbers into the new array. Changes to the string or number in one array does not affect the other array.


javascript:alert('abcde'.slice(-3,-2)); // c


update: 測試的結果是IE 6的substr第一個參數不可為負數, 所以如果要cross browser的話, 不管是substring, substr 第一個參數皆不可為負

update2: ie6的slice 用在 string 上兩個參數都可以為負數

10/03/2007

JavaScript event出現順序

1. mouse event
Javascript - Mouse Events

  • single click: mouse down->mouse up->click
  • double click: mouse down->mouse up->click->mouse down->mouse up->click->dobule click


2. keyboard event
JavaScript - Detecting keystrokes
  • keydown->keypress->keyup

CSS2: outline

CSS2 introduces a last major piece of user interface styling: outlines. An outline is sort of a like a border, but there are two very important differences. First, outlines do not participate in the flow of the document like borders do, and thus don't trigger document reflow as they appear and disappear. If you give an element a 50-pixel outline, the outline will very likely overlap other elements. Second, outlines can be nonrectangular—but don't start leaping for joy just yet. This does not mean that you can create circular outlines. Instead, it means that an outline on an inline element may not act like a border would on that same element. With an outline, a user agent is allowed to "merge" the pieces of the outline to create a single continuous, but nonrectangular, shape. Figure 13-10 shows an example.

firefox idiom ie truebody


function ietruebody(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

http://blog.rexsong.com/?p=183

10/02/2007

javascript idiom: attachevent+detachEvent vs. addEventListener+removeEventListener

if (target.addEventListener) target.addEventListener("mouseout", mouseout,
false); // DOM
else if (target.attachEvent) target.attachEvent("onmouseout", mouseout); // IE
else target.onmouseout = mouseout; // tradition

if (target.removeEventListener)
target.removeEventListener("mouseout", mouseout, false); // DOM
else if (target.detachEvent) target.detachEvent("onmouseout",mouseout); // IE
else target.onmouseout = null; // tradition

javascript idiom: stopPropagation+preventDefault vs. cancelBubble+returnValue

if (event.stopPropagation) event.stopPropagation( ); // DOM Level 2
else event.cancelBubble = true; //IE

// prevent default action
if (event.preventDefault) event.preventDefault( ); // DOM Level 2
else event.returnValue = false; // IE

mouseover, mouseout專用: relatedTarget, fromElement, toElement

Refers to an Element that is related to the target node of the event. For mouseover events, it is the Element the mouse left when it moved over the target. For mouseout events, it is the Element the mouse entered when leaving the target. relatedTarget is undefined for other types of mouse events.


fromElement, toElement
fromElement specifies the document element that the mouse came from for mouseover events. toElement specifies the document element that the mouse has moved to for mouseout events. Comparable to the relatedTarget property of the DOM MouseEvent object.

Test for onmouseover & onomuseOut & relatedTarget & fromElement & toElement

Test for onmouseover & onomuseOut & relatedTarget & fromElement & toElement
I will describe this thoroughly when I am available.

***********************
Mouse Events
http://www.quirksmode.org/js/events_mouse.html