ログインしてさらにmixiを楽しもう

コメントを投稿して情報交換!
更新通知を受け取って、最新情報をゲット!

Fillo Design - WEBデザイン好きコミュのJava Scriptに関するTips

  • mixiチェック
  • このエントリーをはてなブックマークに追加
本格的なのはものすごく長いので
ちょっとした小技をご紹介。

ちなみに私はJava Script組めませんから!(ぁ

コメント(19)

【画像の大きさぴったりにウィンドウを開く】
画像の大きさを読み取ってウィンドウオープン。
ブラウザによって違うかも。

◆<head>内に記述◆

<SCRIPT language="JavaScript">
<!--
function imgwin(img,w,h) {
win1=window.open("","win","width="+w+",height="+h);
with(win1.document){
write("<html><head><title>写真</title></head>");
write("<body leftmargin=0 topmargin=0 marginwidth=0 marginheight=0>");
write("<a href='JavaScript:void(0)' onClick='window.close()'><img src='"+img+"' border=0></a>");
write("</body></html>");
close();
}
}
//-->
</script>

◆<body>内に記述◆

<a href="JavaScript:void(0)" onClick="imgwin('ph.jpg',448,298)"><img src="phs.jpg" width="150" height="100" alt="" border="0"></a>
   
<a href="JavaScript:void(0)" onClick="imgwin('ph2.jpg',335,459)"><img src="ph2s.jpg" width="150" height="100" alt="" border="0"></a>
【入力項目をチェックする】
CGIに確認させるのが面倒だったので...

◆<head>内に記述◆
<script language="JavaScript">
<!--
function check(fObj){
if(!!fObj.style){
if(!fObj.myName.value) fObj.myName.style.backgroundColor = '#FFCC66';
if(!fObj.myAdd.value) fObj.myAdd.style.backgroundColor = '#FFCC66';
}
if(!!fObj.myName.value && !!fObj.myAdd.value){
return true;
} else {
alert('必須項目を全て入力してください')
return false;
}
}
// -->
</script>

◆<body>内に記述◆
<form onSubmit="return check(this)" action="sample">

お名前:<input type="Text" size="30" name="myName">(必須)<br>
ご住所:<input type="Text" size="30" name="myAdd">(必須)<br>
E-mail:<input type="Text" size="30" name="myMail"><br>

<input type="Submit" value="送信">

</form>
【閲覧中のホームページのURLを表示させる】
404のエラー画面からパクりました。

<head>
<script>
function Homepage(){
// in real bits, urls get returned to our script like this:
// res://shdocvw.dll/http_404.htm#http://www.DocURL.com/bar.htm

//For testing use DocURL = "res://shdocvw.dll/http_404.htm#https://www.microsoft.com/bar.htm"
DocURL = document.location.href;

//this is where the http or https will be, as found by searching for :// but skipping the res://
protocolIndex=DocURL.indexOf("://",4);

//this finds the ending slash for the domain server
serverIndex=DocURL.indexOf("/",protocolIndex + 3);

//for the href, we need a valid URL to the domain. We search for the # symbol to find the begining
//of the true URL, and add 1 to skip it - this is the BeginURL value. We use serverIndex as the end marker.
//urlresult=DocURL.substring(protocolIndex - 4,serverIndex);
BeginURL=DocURL.indexOf("#",1) + 1;
if (protocolIndex - BeginURL > 7)
urlresult=""

urlresult=DocURL.substring(BeginURL,serverIndex);

//for display, we need to skip after http://, and go to the next slash
displayresult=DocURL.substring(protocolIndex + 3 ,serverIndex);

// Security precaution: must filter out "urlResult" and "displayresult"
forbiddenChars = new RegExp("[<>\'\"]", "g"); // Global search/replace
urlresult = urlresult.replace(forbiddenChars, "");
displayresult = displayresult.replace(forbiddenChars, "");

document.write('<A target=_top HREF="' + urlresult + '">' + displayresult + "</a>");

}
</script>
</head>


本文に↓

<script> Homepage(); </script>
【新しい画面を画像のサイズにあわせて開く】
画像のサイズを新しいウィンドウに送り、リサイズします。

親ウィンドウのソース:
<HTML>
<HEAD>
<SCRIPT Language="JavaScript">
<!--
function openNew(pic) {
document.picName.picItem.value = pic;
newWin = window.open("subpic.htm","newWin","menubar=0");
}
-->
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="picName">
<INPUT TYPE="hidden" NAME="picItem">
</FORM>
<A HREF="javaScript:void(0)" onClick="openNew('images/sample01.jpg')">サンプル1</A>
<A HREF="javaScript:void(0)" onClick="openNew('images/sample02.jpg')">サンプル2</A>
</BODY>
</HTML>

子(sub)ウィンドウのソース:
<HTML>
<HEAD>
<SCRIPT Language="JavaScript">
<!--
window.resizeTo(10,10);
window.focus();
-->
</SCRIPT>
</HEAD>
<BODY TOPMARGIN="0" LEFTMARGIN="0">
<SCRIPT Language="JavaScript">
<!--

//ブラウザの種類を判定
NN=navigator.appName;

//親ウィンドウから表示する画像を取得
strPic=opener.document.picName.picItem.value;

//画像書き出し
document.open();
document.write("<IMG SRC='",strPic,"'>");
document.close();

//画像の読み込み状況を調べる
timerID=setTimeout("check()",200);

function check() {
clearTimeout(timerID);
flag=true;

if(document.images[0].complete==false)
flag=false;

if(flag==true) {
//ブラウザがIEの場合の幅と高さを取得
if(NN.indexOf("Micro")>=0) {
setW=document.images[0].width+10;
setH=document.images[0].height+30;
window.resizeTo(setW,setH);
} else {
//ブラウザがNetscapeの場合の幅と高さを取得
setW=document.images[0].width;
setH=document.images[0].height+77;
window.innerWidth=setW;
window.innerHeight=setH;
}
} else {
timerID=setTimeout("check()",200);
}
}
-->
</SCRIPT>
</BODY>
</HTML>
【「前のページへ戻る」リンク】
NN,Safariで有効にならないバグ解消済み

hrefをはずす。
リンクとしてカーソルが変化しないので、
CSSでカーソルをポインタにする。

style="cursor:pointer;"
<A onClick="history.back()">前画面に戻る</A>
<a onClick="history.go(-1)">前画面に戻る</a>
【focusメソッド】
珍しく学習したらしい

ウィンドウ名.focus() ・・・・・ウィンドウを前面へ移動

参考サイト:
http://www.htmq.com/js/window_focus.shtml

HTMLソース
<html>
<head>
<script type="text/javascript" language="javascript">
<!--
function sample1() {
sample=window.open() ;
sample.blur();
}

function sample2() {
sample.focus();
}
// -->
</script>
</head>
<body>
<a onclick="sample1()">ここをクリックするとsampleウィンドウが開き、同時にsampleウィンドウからフォーカスがはずれます。</a><br>
<a onclick="sample2()">ここをクリックするとsampleウィンドウにフォーカスがあたります。</a>
</body>
</html>
【キー操作を制御する】
せっかくの隠しリンクが
キーボードごときに見つかると腹立つので設置しました

//------------------------------------------------------------------------------
//BackSpaceキー押下防止
//------------------------------------------------------------------------------
//キー押下時
window.document.onkeydown=onKeyDown;

//BackSpaceキー押下防止
function onKeyDown(e) {

if (navigator.appName == "Microsoft Internet Explorer") {

//ALT+←ダメ
if( event.keyCode == 0x25 && event.altKey == true ) {
//alert("ALT+←はダメ!");
return false ;
}
//テキストボックス、パスワードボックスは許す
for (i = 0; i < document.all.tags("INPUT").length; i++) {
if (document.all.tags("INPUT")(i).name == window.event.srcElement.name &&
(document.all.tags("INPUT")(i).type == "text" || document.all.tags("INPUT")(i).type == "password") &&
document.all.tags("INPUT")(i).readOnly == false){
return true;
}
}
//テキストエリアは許す
for (i = 0; i < document.all.tags("TEXTAREA").length; i++) {
if (document.all.tags("TEXTAREA")(i).name == window.event.srcElement.name &&
document.all.tags("TEXTAREA")(i).readOnly == false){
return true;
}
}
//BackSpaceダメ
if( event.keyCode == 8 ) {
//alert("BackSpaseはダメ!");
return false ;
}
  } else
  if (navigator.appName == "Netscape") {
  if (e.which == 8) {
   return false;
   }
}
}

参考サイト:
http://chaichan.hp.infoseek.co.jp/qa4000/qa4304.htm
【開いた画面を閉じる】

そのまんまです。
「閉じる」ボタン等のアンカータグに設定。

a href="#" onclick="window.close()"
【小窓を指定サイズで開く】

毎度忘れてしまうので。

href="javascript:w=window.open('pages.html','','scrollbars=no,Width=420,Height=250');w.focus();"

分ける場合はこう↓

>ヘッダースクリプト
function OpenWindow(URL,Winname,Width)
{SubWindow=window.open(URL,Winname,"width=620,height=660,scrollbars=yes,toolbar=no,location=no,status=no,directories=no,resizable=yes,");
}

>本文
a href="javascript:OpenWindow('kiss.html','SubWindow');"

開いた画面を手前に出すバージョン↓
<script language="JavaScript"><!--
function openwin(message) {
w = window.open("", "msg2", "alwaysRaised=yes");
w.focus();
w.document.open();
w.document.write(message);
w.document.close();
}
// --></script>
【埋め込まれたWMPをボタンクリックで全画面表示させる】

現在ページ内に埋め込まれたメディアプレイヤー(再生中)を
プレイヤー外のリンクボタンクリックで最大化表示させます。

今回もあと一歩のところでわからなかったので
同僚さんにお手伝いしていただきました(´д`;)感謝!

ActiveX対策のためにWMPは外部スクリプトで呼び出します。

HTML側に:
<div id="player" align="left">

<script type="text/javascript">
<!--
/* CreateWindowsMediaPlayerObj(
ムービーへのパス,
ムービーの幅,
ムービーの高さ,
コントロール表示の有無,
自動再生の有無,
ステータスバー表示の有無
)
*/
htmWMP=CreateWindowsMediaPlayerObj(
"asx/yoku9_0500.asx",
290,
220,
"true",
"true",
"false"
);
//-->
</script>
</div>

<div id="v_big"><a href="#" onclick="return fullScreen();">全画面で再生</a></div>
</div>

JavaScript:
//フルスクリーン表示
function fullScreen()
{
var player = document.WMP;
player.fullScreen = "true";
}

/*
* @param fpas ムービーへのパス(相対パス可)
* @param width ムービーの幅
* @param height ムービーの高さ
* @param f_controll コントロール表示の有無
* @param f_auto 自動再生の有無
* @param f_status ステータスバー表示の有無
*/

function CreateWindowsMediaPlayerObj(fpass,width,height,f_controll,f_auto,f_status){
htm="";
if(f_controll=="true"){ // コントロール表示の場合はコントロールの高さ(45px)をプラス
height=eval(height+45);
}
if(f_status=="true"){ // ステータスバー表示の場合はステータスバーの高さ(24px)をプラス
height=eval(height+24);
}
//OBJECT TAG
htm+="<object";
htm+=" id='WMP'";
htm+=" width='"+width+"' height='"+height+"'";
htm+=" classid='CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6'";

htm+=" >\n";
htm+="<param name='URL' value='"+fpass+"'>\n";
htm+="<param name='ShowControls' value='"+f_controll+"'>\n";
htm+="<param name='AutoStart' value='"+f_auto+"'>\n";
htm+="<param name='ShowStatusBar' value='"+f_status+"'>\n";
htm+="</object>\n";
document.write(htm);
}
【リンクの点線を消す】

地味かつ使いどころのないTips。
active時なんかにリンク部がバレないようにする程度の役割。

onFocus="this.blur()"
【背景画像をランダムに表示させる】

どこで拾ってきたのか忘れてしまったが・・・
とりあえず、JavascriptでCSSを書き換える作業を行います。


<script type="text/javascript">
<!--
bgimg = new Array();
bgimg[0] = "画像URL1";
bgimg[1] = "画像URL2";
bgimg[2] = "画像URL3";
bgimg[3] = "画像URL4";
bgimg[4] = "画像URL5";

document.body.style.cssText += 'background-image: url("' + bgimg[chip] + '");
background-attachment: fixed;';
chip = Math.floor(bgimg.length * Math.random());

// -->
</script>
【ブラウザを閉じる】Vr.2

以前に紹介したスクリプト
a href="#" onclick="window.close()"
では、NNやFxで動作しないことが判明。

検索しまくってやっとソースを見つけました。
IEでもセキュリティーのアラートが出ず、重宝しています。
生憎私にはまだ解析できないけれど・・・(汗

<script language="javascript">
function close_win(){
var nvua = navigator.userAgent;
if(nvua.indexOf('MSIE') >= 0){
if(nvua.indexOf('MSIE 5.0') == -1) {
top.opener = '';
}
}
else if(nvua.indexOf('Gecko') >= 0){
top.name = 'CLOSE_WINDOW';
wid = window.open('','CLOSE_WINDOW');
}
top.close();
}
</script>

参考URL:
http://neta.tbx.jp/textbox/blosxom/note/20050311close.html
【テキストエリア内の文字を1クリックで全選択】

試していないけれど、おもしろそうなのでメモしました。
タグなどコピー用のテキストエリアに使えるかも。

<textarea cols="40" rows="3" onclick="this.focus()" onfocus="this.select()">テキスト</textarea>
【画像を先読みさせておく】

ちょっとしたユーザーへの配慮としてこっそり置いておくと
マウスオーバーなどの画像を
スムーズに表示させることができるTips

画像を表示させずに先読みさせておきます。

<script language="JavaScript">
<!--
imgload = new Image();
imgload.scr = "images/button_on.jpg";
//-->
</script>
【タイピングしているように文字を表示する】

久々に見つけたお遊びタイプなので思わずメモ。
ユーザビリティ的に嫌われがちなので
おしゃれに使いこなしてくださいw
スクリプトはお決まりの<head>内です。

<script language="VBScript">
<!--
Dim counter, txt, txt_len, timerID
Sub Window_onLoad()
txt = txtbox.innerHTML
txt_len = Len(txt)
counter = 1
timerID = Window.SetInterval("typewriter()", 100)
//後の数字が大きいほどスピードは遅い
End Sub
Sub typewriter()
Dim cur
If counter > txt_len Then
cur = ""
Window.ClearInterval(timerID)
Else
cur = "|"
End If
txtbox.innerHTML = Left(txt, counter) & cur
counter = counter + 1
End Sub
//-->
</script>

<div id="txtbox">入力するテキスト</div>

++++++++++++++++++++++++++++++++++++++++++++++++
スタイル例:
<div id="txtbox" style="font-size:12px;border:solid 1px;height:20px;width:400px;line-height:20px;">  タイピングしているように文字を表示</div>
【IME入力を制限する】

って表現でいいのかなあ?(ぁ
テキストフィールドへ入力される文字を半角に統一します。
基本といえば基本かも。

IEだけならCSSで簡単なのですが、
こちらのスクリプトはFx対策もされていて便利。
NNでも動作確認できてます。

参考URL:
http://www.losttechnology.jp/Tips/inputhankaku.html

<script type="text/javascript">
function chkCode(id) {
work='';
for (lp=0;lp<id.value.length;lp++) {
unicode=id.value.charCodeAt(lp);
if ((0xff0f<unicode) && (unicode<0xff1a)) {
work+=String.fromCharCode(unicode-0xfee0);
} else if ((0xff20<unicode) && (unicode<0xff3b)) {
work+=String.fromCharCode(unicode-0xfee0);
} else if ((0xff40<unicode) && (unicode<0xff5b)) {
work+=String.fromCharCode(unicode-0xfee0);
} else {
work+=String.fromCharCode(unicode);
}
}
id.value=work; /* 半角処理のみ */
//id.value=work.toUpperCase(); /* 大文字に統一する場合に使用 */
//id.value=work.toLowerCase(); /* 小文字に統一する場合に使用 */
}
</script>

<input type="text" name="xxxx" value="" onkeyup="chkCode(this);" style="ime-mode:disabled;">
【ロールオーバーで説明用の吹き出しを表示】

今更!?な感じですが。
リンクにロールオーバーすると、吹き出しをポップアップします。
小窓タイプではないです。

ここを参考に
http://www.dhtmlgoodies.com/scripts/bubble-tooltip/bubble-tooltip.html

▼見辛いのでまとめて整頓(画像は各自準備してくださいまし)

<!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=Shift_JIS">

<SCRIPT language="javascript" type="text/javascript">
<!--
function showToolTip(e,text){
if(document.all)e = event;

var obj = document.getElementById('bubble_tooltip');
var obj2 = document.getElementById('bubble_tooltip_content');
obj2.innerHTML = text;
obj.style.display = 'block';
var st = Math.max(document.body.scrollTop,document.documentElement.scrollTop);
if(navigator.userAgent.toLowerCase().indexOf('safari')>=0)st=0;
var leftPos = e.clientX - 20;
if(leftPos<0)leftPos = 0;
obj.style.left = leftPos + 'px';
obj.style.top = e.clientY - obj.offsetHeight -15 + st + 'px';
}

function hideToolTip()
{
document.getElementById('bubble_tooltip').style.display = 'none';

}
//-->
</SCRIPT>

<style>
<!--
#bubble_tooltip{
width:120px;
position:absolute;
//display:none;
background-color:#FFCCCC;
}
#bubble_tooltip .bubble_top{
background-image: url('../images/bubble_top.gif');
background-repeat:no-repeat;
height:10px;
}
#bubble_tooltip .bubble_middle{
background-image: url('../images/bubble_middle.gif');
background-repeat:repeat-y;
background-position:bottom left;
padding:0px 5px 0px 5px;
}
#bubble_tooltip .bubble_middle span{
position:relative;
font-family: Trebuchet MS, Lucida Sans Unicode, Arial, sans-serif;
font-size:11px;
}
#bubble_tooltip .bubble_bottom{
background-image: url('../images/bubble_bottom.gif');
background-repeat:no-repeat;
height:10px;
position:relative;
}
//-->
</style>
</HEAD>
<BODY>
<div id="bubble_tooltip">
<div class="bubble_top"><span></span></div>
<div class="bubble_middle"><span id="bubble_tooltip_content"></span></div>
<div class="bubble_bottom"></div>
</div>
<br /><br /><br /><br />
<a href="#" onmouseover="showToolTip(event,'てすと');return false" onmouseout="hideToolTip()">Roll over me</a>
</BODY>

</html>

ログインすると、残り1件のコメントが見れるよ

mixiユーザー
ログインしてコメントしよう!

Fillo Design - WEBデザイン好き 更新情報

Fillo Design - WEBデザイン好きのメンバーはこんなコミュニティにも参加しています

星印の数は、共通して参加しているメンバーが多いほど増えます。