Webページを構成する各要素はドキュメントの流れに従い通常は上から下へ、左から右へと配置されていく。
そして要素の種類によって改行が入ったり入らなかったりする。
CSSを使う事でこの流れに逆らったレイアウトを実現する事が出来る。
どんな要素も(表示されている以上は)ドキュメント上でのX座標とY座標を持っているが、CSSでの'positionプロパティ'を'static'以外にする事でこれら座標を変える事が出来るようになる。
Javascriptから(prototype.jsを使い)要素をドラッグ可能にするスクリプトを書いてみた。
ソースは以下のような感じだ。
var DragObj = Class.create();
DragObj.prototype = {
initialize: function(elem, styles) {
this.elem = elem;
if (this.elem.getStyle('position') == 'static') this.elem.relativize(this.elem);
this.elem.setStyle(styles);
this.elem.observe('mousedown', this.capture.bindAsEventListener(this));
document.observe('mouseup', this.uncapture.bindAsEventListener(this));
document.observe('mousemove', this.move.bindAsEventListener(this));
},
capture: function(event) {
event.stop();
this.captured = true;
this.diffX = event.pointerX() - (isNaN(parseInt(this.elem.getStyle('left'))) ? 0 : parseInt(this.elem.getStyle('left')));
this.diffY = event.pointerY() - (isNaN(parseInt(this.elem.getStyle('top'))) ? 0 : parseInt(this.elem.getStyle('top')));
this.transparencyIsChanged(100, 30, 10);
},
uncapture: function(event) {
if (this.captured) {
this.captured = false;
this.transparencyIsChanged(30, 100, 10);
}
},
move: function(event) {
event.stop();
if (this.captured) {
this.moved = true;
this.elem.setStyle({
top: event.pointerY() - this.diffY + 'px',
left: event.pointerX() - this.diffX + 'px'
});
} else {
this.moved = false;
}
},
transparencyIsChanged: function(start, end, inc) {
var opacity = start;
var elem = this.elem;
if (start > end) {
opacity = -start;
end = -end;
}
setTimeout(function() {
opacity += inc;
elem.setOpacity(Math.abs(opacity) / 100);
if (opacity < end) setTimeout(arguments.callee, 30);
}, 30);
}
}
使い方は
new DragObj(elem)
とするだけ。
一緒にスタイルも設定したい時は
new DragObj(elem, {
padding: '5px',
fontSize: '12px',
cursor: 'move'
});
こんな具合で呼び出しすればいい。
こちらのサンプルでは開くと写真が5枚通常に配置され、DIVボックスが10個ランダムに配置されそれらすべてがドラッグ可能になっている。
カテゴリ:
トラックバック(0)
トラックバックURL: http://blog.beanz-net.jp/beanz_mtos/mt-tb.cgi/47
コメントする