私は初心者のJavaScriptプログラマーです。Lightbox 2に似たものを作成しようとしていますが、はるかに単純です。自分で一からやりたいのは、学ぶためだけです。しかし、私はそれが画像を表示する最後の重要な部分で立ち往生しています。問題は、匿名関数に割り当ててonclickを使用しようとするところにあると思います。elem[i] .onclick = function(){liteBoxFocus(imgSource、imgTitle); falseを返します;}; 。私のコードを実行してグーグルのロゴをクリックしてみると、グーグルのロゴとタイトルの代わりにヤフーのロゴとタイトルが表示されます。ただし、yahooロゴをクリックすると正常に機能するため、無名関数は最後のループでのみ保持されるようです。前もって感謝します!!!
便宜上、CSS / JS/XHTML全体を1つのページに配置しました。
<html>
<頭>
<title>エリックのスクリプト</title>
<style type = "text / css">
#liteBoxBg、#liteBox {
表示:なし;
}
#liteBoxBg {
背景色:#000000;
高さ:100%;
幅:100%;
マージン:0px;
位置:固定;
左:0px;
上:0px;
filter:alpha(opacity = 80);
-moz-不透明度:0.8;
-khtml-不透明度:0.8;
不透明度:0.8;
z-index:40;
}
#liteBox {
背景色:#fff;
パディング:10px;
位置:絶対;
トップ10%;
ボーダー:1pxソリッド#ccc;
width:auto;
text-align:center;
z-index:50;
}
</ style>
<script type = "text / javascript">
window.onload = start;
関数start(){
var imgTitle="タイトルなし";
var imgSource;
var elem = document.getElementsByTagName( "a");
var i;
//DIVを動的に挿入して効果を生み出します
var newDiv = document.createElement('div');
newDiv.setAttribute( "id"、 "liteBox");
document.getElementsByTagName( "body")[0] .appendChild(newDiv);
newDiv = document.createElement('div');
newDiv.setAttribute( "id"、 "liteBoxBg");
document.getElementsByTagName( "body")[0] .appendChild(newDiv);
//これらのアンカーをrel=liteboxで確認します
for(i = 0; i <elem.length; i ++){
if(elem [i] .rel == "litebox"){
imgSource = elem [i] .href.toString();
imgTitle = elem [i] .title;
elem [i] .childNodes [0] .style.border = "0px solid #fff";
elem [i] .onclick = function(){liteBoxFocus(imgSource、imgTitle); falseを返します;};
}
}
//前景をクリックしたら、ライトボックスを閉じます
document.getElementById( "liteBoxBg")。onclick = liteBoxClose;
}
//フォーカスのある画像を表示します
関数liteBoxFocus(source、title){
document.getElementById( "liteBox")。style.display = "block";
document.getElementById( "liteBox")。innerHTML = "<h1>" + title + "</ h1>" +
"<img src='"+ソース+"'/><br />" +
"<a href='#' onclick='liteBoxClose().'> <img src ='images / litebox_close.gif' border = '0' alt ='close' /> </a>";
document.getElementById( "liteBoxBg")。style.display = "block";
}
//ライトボックスを閉じます
関数liteBoxClose(){
document.getElementById( "liteBox")。style.display = "none";
document.getElementById( "liteBoxBg")。style.display = "none";
falseを返します。
}
</ script>
</ head>
<本体>
<a href="http://www.google.com/intl/en_ALL/images/logo.gif" rel="litebox"title="Googleロゴ"><imgsrc="http://www.google。 com / intl / en_ALL / images / logo.gif "alt =" "/> </a>
<a href = "
http://www.barbariangroup.com/assets/users/bruce/images/0000/4121/yahoo_logo.jpg "rel =" litebox "title =" Yahooo Logo "> <img src ="
http://www.barbariangroup.com/assets/users/bruce/images/0000/4121/yahoo_logo.jpg "alt =" "/> </a>
</ body>
</ html>