前端集合 - 关注前端技术和互联网免费资源

关注前端技术和互联网免费资源

分类儿

页面儿

搜索儿

前端集合 RSS订阅
Home » 前端集合 » window.location.hash妙用

window.location.hash妙用

发布者:前端集合 // 发布时间:2011-11-12 17:27:43 // 分类:前端集合 // 访问: 4,434 次 // 热度:

这2天在工作碰到了一个问题, 我想到了使用window.location.hash来解决. 下面讲讲详细经过:

1. 需求介绍

有2个页面:a.htm 和 b.htm.

a.htm上面有3个缩略图, b.htm 上面有5个(可以是更多, 反正要大于3个)的大图片. 其中3个缩略图与b.htm上的某3个图片有对应关系.

现在客户需要这样一个效果:

在页面a.htm的3缩略图上分别加3个链接, 分别链接到b.htm对应的大图上. 并且b.htm上的其他图片全部不能显示. 比如点击a.htm的第一张缩略图, 那么b.htm只能显示第一张缩略图对于的大图, 其他4张图片全部隐藏.  而且不能改变现有链接a.htm和b.htm.

2. 需求分析

既然不能改变现有链接a.htm和b.htm, 那么我就想到每个链接后面不是都可以添加锚链接#xxx么. 所以我就想可不可以通过使用a.htm#1, a.htm#2, a.htm#3这种形式来达到控制b.htm上显示不同图片的目的?

经过实践证明, 这种方法是可行的.

3. 如何实现

在a.htm设置如下代码:

<a href="b.htm#1" target="_blank"> <img src="1.jpg" alt="image 1" /></a><br />
<a href="b.htm#2" target="_blank"> <img src="2.jpg" alt="image 2" /></a><br />
<a href="b.htm#3" target="_blank"> <img src="3.jpg" alt="image 3" /></a><br />

在b.htm设置如下代码:

<img id="1" src="big-1.jpg" alt="image 1" />
<img id="2"  src="big-2.jpg" alt="image 2" />
<img id="3"  src="big-3.jpg" alt="image 3" />
<img id="4"  src="big-4.jpg" alt="image 4" />
<img id="5"  src="big-5.jpg" alt="image 5" />

b.htm中的Javascript是重点:

var hash = window.location.hash;
                hash = hash.replace('#','');
                if (hash != '' && hash != null && typeof(hash) != 'undefined') {
                    if (document.getElementById(hash)) {
                        document.getElementById(hash).style.display = "inline";
                    }
                }

浏览Demo查看实际效果

Tags: JavaScript, window.location.hash, location.hash, js

一些知识>>  << 新版Google Reader上线, 几点不爽之处
Top