2010年4月18日

JavaScriptと正規表現

Filed under: JavaScript — admin @ 1:24 AM

var r = /^([-+]?[0-9]*)\.?([0-9]*[1-9])?$/;

var a = r.exec (123.0450);
a[1];  // '123'
a[2];  // '045'

var b = r.exec (123.0);
b[1];  // '123'
b[2];  // undefined

3年前のdocumentから発掘。

2010年3月29日

iframeをJavaScriptで扱う

Filed under: JavaScript — admin @ 5:04 AM

var iframe = document.getElementById('iframe').contentWindow;

2010年3月3日

画像のオリジナルサイズをJavaScriptで取得する

Filed under: JavaScript — admin @ 12:57 AM

getNaturalSizeにimageオブジェクトを投げてあげるとオブジェクトが返る。

var cache = [];
var getNaturalSize = (function(){
    if(Image.naturalWidth || Image.naturalHeight){
        return function(image){
            return {
                "width"  : image.naturalWidth,
                "height" : image.naturalHeight
            };
        }
    }
    else if(window.opera){
        return function(image){
            if(!cache[image.src]){
                var mem = {
                    "w": image.width,
                    "h": image.height
                };
                image.removeAttribute("width");
                image.removeAttribute("height");
                w = image.width;
                h = image.height;
                image.width = mem.w;
                image.height = mem.h;
                cache[image.src] = {
                    "width"  : w,
                    "height" : h
                };
            }
            return cache[image.src];
        };
    }
    else if(window.attachEvent){
        return function(image){
            if (image[key] && image[key].src === image.src) {
                return image[key];
            }
            run = image.runtimeStyle;
            mem = {
                "w" : run.width,
                "h" : run.height
            }; // keep runtimeStyle
            run.width  = "auto"; // override
            run.height = "auto";
            w = image.width;
            h = image.height;
            run.width  = mem.w; // restore
            run.height = mem.h;
            image[key] = {
                "width"  : w,
                "height" : h,
                "src"    : image.src
            };
            return image[key]; // bond
        }
    }
    else{
        return function(image){
            return {
                "width"  : 100,
                "height" : 100
            };
        }
    }
})();

Firefox、IE6~8、Chrome、Operaで動作する。Safari未検証。

image.naturalWidthやimage.naturalHeightはイメージがロードされるまでは初期値の0がセットされている。従ってロード時にjsを実行し、imgの読み込みがjsよりも後だった場合に、正しい値が取得できない。以下のコードを使用すると解決できる。

var setActualSize = function(image, callback) {
    var img    = new Image();
    img.src    = image.src;
    img.onload = function() {
        var actual = {
            "width"  : img.width,
            "height" : img.height
        };
        img.onload = "";
        img = void 0;
        callback(actual);
    };
}

2010年2月22日

スクロール位置を取得する

Filed under: JavaScript — admin @ 3:19 AM

var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;// ex) 100(px)

2010年2月14日

createElementでtableを挿入するときのIEの挙動

Filed under: JavaScript — admin @ 3:48 AM

以下のコードはIE以外では正常に動作する。

var table = document.createElement('table');
var tr = document.createElement('tr');
var td = document.createElement('td');
var img = document.createElement('img');
document.getElementById('container').appendChild(table).appendChild(tr).appendChild(td).appendChild(img);

以下のコードはIEでも動作する。違いはtbodyを明示してあげる事。

var table = document.createElement('table');
var tbody = document.createElement('tbody');
var tr = document.createElement('tr');
var td = document.createElement('td');
var img = document.createElement('img');
document.getElementById('container').appendChild(table).appendChild(tbody).appendChild(tr).appendChild(td).appendChild(img);

html 4.01

11.2.3 行グループ: THEAD、 TFOOT、及びTBODY要素

TBODY開始タグは、表が本体をただ1つだけ含んでいてヘッダもフッタも含まないという場合を除き、常に必要である。

へー

html 5

table 要素

0 個以上の tbody 要素

ふむふむ

参考

http://w3g.jp/xhtml/dic/tbody

2010年1月29日

IEはradioボタンをappendChildしてもつかえない

Filed under: JavaScript,jQuery — admin @ 2:03 AM

IE6~7でラジオボタンをappendChildした場合、そのラジオボタンはクリックできない。ラジオボタンとして致命的なバグである。

■失敗例

以下のようにDOM要素を操作する。

var input = document.createElement('input');
var p     = document.createElement('p');
p.appendChild(input);

ちなみにjQueryを使うと以下のようになる。

var input = document.createElement('input');
var p     = document.createElement('p');
$(p).append(input);

■解決策

IEだけinnerHTMLを使う。

var input = document.createElement('input');
var p     = document.createElement('p');
if(!!(!window.opera && window.attachEvent)){
    p.innerHTML = '<input type="radio" name="id" />';
}
else{
    p.appendChild(input);
}

ちなみにjQueryを使うと以下のようになる。

var input = document.createElement('input');
var p     = document.createElement('p');
if($.browser.msie){
    $(p).append('<input type="radio" name="id" />');
}
else{
    $(p).append(input);
}

2010年1月27日

Shadowboxの設定

Filed under: JavaScript — admin @ 1:24 AM

以下のようにHTML側で設定する。

<a href="#" id="shadowbox" rel="shadowbox;width=450;height=110;">open window</a>

script側でも以下のように設定した場合、上手く動作しないことがある。

Shadowbox.open({
    "content" : 'this is a shadow box',
    "player"  : "html",
    "width"   : 300,
    "height"  : 200,
    "options" : {
        "onFinish" : function(){
            alert('test');
        }
    }
});

onFinishが上手く動作しなかった。設定ミスに起因するが、見つけにくいミスでもある。

2010年1月23日

JavaScriptで画像を縦横比を維持しつつ指定サイズに丸める

Filed under: JavaScript,jQuery — admin @ 6:02 PM

SVGやcanvasを使えば確かそのままトリミングもできた気がするが、別にそこまでしたくない用の関数。画像のオリジナルサイズを取得し計算する感じだ。面倒なのでjQueryを使う。

var frameWidth  = 700;
var frameHeight = 400;
$('li').css({
    "overflow" : "hidden"
});
$('li img').each(function(){
    var nWidth  = this.naturalWidth  || getNaturalSize(this).width;//ff : ie
    var nHeight = this.naturalHeight || getNaturalSize(this).height;//ff : ie
    if(nHeight < nWidth * (frameHeight / frameWidth)){
        this.width  = nWidth * frameHeight / nHeight;
        this.height = frameHeight;
        $(this).css({
            "width"  : nWidth * frameHeight / nHeight + 'px',
            "height" : frameHeight + 'px',
            "position" : "relative",
            "left" : -((nWidth * frameHeight / nHeight) - frameWidth) / 2 + 'px'
        });
    }
    else{
        this.width  = frameWidth;
        this.height = nHeight * frameWidth / nWidth;
        $(this).css({
            "width"  : frameWidth + 'px',
            "height" : nHeight * frameWidth / nWidth + 'px',
            "position" : "relative",
            "top" : -((nHeight * frameWidth / nWidth) - frameHeight) / 2 + 'px'
        });
    }
});

以下の部分でブラウザ分岐をしている。IEとOpera以外はimgオブジェクトにオリジナルのサイズが格納されたプロパティ(naturalWidth、naturalHeight)を持つ。

var nWidth  = this.naturalWidth  || getNaturalSize(this).width;//ff : ie
var nHeight = this.naturalHeight || getNaturalSize(this).height;//ff : ie

getNaturalSize関数は以下のようになる。

var getNaturalSize = function(image){
    var w, h, key = "actual", run, mem;
    if(window.opera){
    }
    if (image[key] && image[key].src === image.src) {
        return image[key];
    }
    run = image.runtimeStyle;
    mem = {
        "w" : run.width,
        "h" : run.height
    }; // keep runtimeStyle
    run.width  = "auto"; // override
    run.height = "auto";
    w = image.width;
    h = image.height;
    run.width  = mem.w; // restore
    run.height = mem.h;
    image[key] = {
        "width"  : w,
        "height" : h,
        "src"    : image.src
    };
    return image[key]; // bond
};

ちなみにOperaには対応していない。

2010年1月17日

Shadowboxでショートカットキーを使えなくする

Filed under: JavaScript — admin @ 9:53 PM

Shadowboxでは「x」や「w」のキーを押すとウィンドが閉じる。しかし、入力欄などがShadowbox内に存在していた場合、この挙動が不具合を生じさせる。そこで以下のようにenableKeysオプションをfalseにする。

Shadowbox.init({
    "language" : 'ja',
    "players"  : ['img', 'html', 'iframe', 'qt', 'wmp', 'swf', 'flv'],
    "enableKeys" : false
});

2010年1月17日

tinyMCEはjQueryのcloneで複製できない

Filed under: JavaScript,jQuery — admin @ 3:06 AM

jQueryのtinyMCEプラグインを使用する。

■cloneメソッド

そっくりそのままコピーができるが、コピーされたtinyMCEは機能しないはずだ。この不具合は、tinyMCEをsortable要素にした時にも生じる。恐らく、tinyMCEが内部的にiframeを使用していることに起因するのではないだろうか。

<!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>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.js"></script>
<script type="text/javascript" src="tiny_mce/tiny_mce.js"></script>
<script type="text/javascript" src="tiny_mce/jquery.tinymce.js"></script>
<script type="text/javascript">
$(function(){
	$('textarea.tinymce').tinymce({
		theme : "advanced",
		plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
		theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
		theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
		theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
		theme_advanced_toolbar_location   : "top",
		theme_advanced_toolbar_align      : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true,
		init_instance_callback : function(){
			var clone = $('div.parts').clone(true);
			$('div.parts').after(clone);
		}
	});
});
</script>
</head>
<body>
<div class="parts">
<form method="post" action="">
<textarea class="tinymce" name="" rows="15" cols="60"></textarea>
</form>
</div>
</body>
</html>

■解決策

document.createElementでtextareaから生成したtextareaに対して、tinymce()する。

<!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>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.js"></script>
<script type="text/javascript" src="tiny_mce/tiny_mce.js"></script>
<script type="text/javascript" src="tiny_mce/jquery.tinymce.js"></script>
<script type="text/javascript">
$(function(){
	$('textarea.tinymce').tinymce({
		theme : "advanced",
		plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
		theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
		theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
		theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
		theme_advanced_toolbar_location   : "top",
		theme_advanced_toolbar_align      : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true,
		init_instance_callback : function(){
			var div      = document.createElement('div');
			var form     = document.createElement('form');
			var textarea = document.createElement('textarea');
			$(div).attr('class', 'parts');
			$(div).append(form);
			$(form).append(textarea);
			$(textarea).attr('class', 'tinymce');
			$(textarea).attr('rows', '15');
			$(textarea).attr('cols', '60');
			$('div.parts:last').append(div);
			$(textarea).tinymce({
				theme : "advanced",
				plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
				theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
				theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
				theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
				theme_advanced_toolbar_location   : "top",
				theme_advanced_toolbar_align      : "left",
				theme_advanced_statusbar_location : "bottom",
				theme_advanced_resizing : true
			});
		}
	});
});
</script>
</head>
<body>
<div class="parts">
<form method="post" action="">
<textarea class="tinymce" name="" rows="15" cols="60"></textarea>
</form>
</div>
</body>
</html>

しっかり機能するtinyMCEが生成されるはずだ。

init_instance_callback

エディタが完成するとコールされる。tinymce()から完成までは時間がかかり、気をつけなくてはいけないのは、その間にscript処理が止まらない。従って、完成した(直後の)エディタに対してscriptからアクセスする場合は、init_instance_callbackを使用する必要がある。

« 前ページへ次ページへ »