js图片库——改进版

《JavaScript+DOM编程艺术》一书作者给前端程序员的忠告:

1)留后路:在浏览器禁用js的时候基本功能要保证。href要设置成真实存在的url,慎用javascript伪协议,慎用弹窗。

2)分离javascript:js代码单独写入一个文件,减少它对html的依赖,在html中尽量去引用它,而不是直接插入js。

3)向后兼容:充分照顾旧版本的浏览器,在实现一些功能的时候多做判断。

在此基础上对小项目的修改(原来的版本:http://blog.csdn.net/lishichengyan/article/details/77759324

1)html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
	<head>
		<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
		<title>Image Gallery</title>
		<script type="text/javascript" src="scripts/showPic.js"></script>
		<link rel="stylesheet" href="styles/layout.css" type="text/css" media="screen"/>
	</head>
	<body>
		<h1>Famous Paintings</h1>
		<ul id="imagegallery">
			<li>
				<a href="images/snowstorm.jpg" title="snow storm by Turner">
				Snowstorm</a>
			</li>
			<li>
				<a href="images/sunflowers.jpg" title="sunflowers by van Gogh">
				Sunflowers</a>
			</li>
			<li>
				<a href="images/selfportrait.jpg" title="double self portrait by Schiller">
				Selfportrait</a>
			</li>
			<li>
				<a href="images/traveller.jpg" title="an oil painting by Caspar David Friedrich">
				Traveller</a>
			</li>
		</ul>
		<img id="placeholder" src="images/placeholder.jpg" alt="my image gallery"/>
		<p id="description">Choose an image.</p>
	</body>
</html>
2)css:

body{
	font-family:"Helvetica","Arial",serif;/*设置字体*/
	color:#333;
	background-color:#ccc;
	margin:1em 10%;/*设置四个边距,顺序是:上右下左*/
}
/*
h1{
	color:#333;
	background-color:transparent;
}
*/
a{
	color:#c60;
	background-color:transparent;
	font-weight:bold;
	text-decoration:none;
}

ul{
	padding:0;/*设置内边距*/
}
/*
li{
	float:left;
	padding:1em;
	list-style:none;
}
*/
#imagegallery{
	list-style:none;
}

#imagegallery li{
	display:inline;
}

#imagegallery li a img{
	border:0;
}

3)js:

window.onload=function(){
	prepareGallery();
}

function prepareGallery(){
	if(!document.getElementsByTagName) return false;
	if(!document.getElementById) return false;
	if(!document.getElementById("imagegallery")) return false;
	var gallery=document.getElementById("imagegallery");
	var links=gallery.getElementsByTagName("a");
	for(var i=0;i<links.length;i++){
		links[i].onclick=function(){
			return showPic(this);
		}
	}
}

function showPic(whichpic){
	if(!document.getElementById("placeholder")) return true;
	var source=whichpic.getAttribute("href");
	var placeholder=document.getElementById("placeholder");
	if(placeholder.nodeName!="IMG") return true;
	placeholder.setAttribute("src",source);//注意source不要用""
	if(!document.getElementById("description")) return false;
	var text=whichpic.getAttribute("title")?whichpic.getAttribute("title"):"";
	var description=document.getElementById("description");
	if(description.firstChild.nodeType==3){
		description.firstChild.nodeValue=text;
	}
	return false;
}
运行效果:



阅读更多
换一批

没有更多推荐了,返回首页