JavaScript 图像弹出窗口
一种简单的在鼠标悬停在较小图像上时显示弹出图像的方法。
引言
很多时候,开发人员需要在用户将鼠标指针悬停在缩略图上时显示更大的弹出图像。我将在这里解释一个非常简单的 JavaScript,它可以用来显示弹出图像。该脚本经过测试,在 IE 7.0 和 Mozilla Firefox 3.0 中运行良好。
实施步骤
- 在 HTML 页面上创建一个名为“
imgbox
”的DIV
,你的缩略图将显示在该页面上。DIV
和与DIV
关联的 CSS 元素 ID 如下所示 - 这是显示弹出图像的 JavaScript 代码
- 获取缩略图图像的左侧和顶部位置
- 获取缩略图图像源,使
DIV
可见,增加高度和宽度到所需大小,并将图像附加到DIV
。 - 在鼠标移出时隐藏
DIV
。 - 为缩略图图像添加一个
OnMouseOver
客户端事件调用,以便在鼠标悬停时显示弹出图像。
<div id="imgbox"></div>
CSS 元素
#imgbox
{
vertical-align : middle;
position : absolute;
border: 1px solid #999;
background : #FFFFFF;
filter: Alpha(Opacity=100);
visibility : hidden;
height : 200px;
width : 200px;
z-index : 50;
overflow : hidden;
text-align : center;
}
function getElementLeft(elm)
{
var x = 0;
//set x to elm’s offsetLeft
x = elm.offsetLeft;
//set elm to its offsetParent
elm = elm.offsetParent;
//use while loop to check if elm is null
// if not then add current elm’s offsetLeft to x
//offsetTop to y and set elm to its offsetParent
while(elm != null)
{
x = parseInt(x) + parseInt(elm.offsetLeft);
elm = elm.offsetParent;
}
return x;
}
function getElementTop(elm)
{
var y = 0;
//set x to elm’s offsetLeft
y = elm.offsetTop;
//set elm to its offsetParent
elm = elm.offsetParent;
//use while loop to check if elm is null
// if not then add current elm’s offsetLeft to x
//offsetTop to y and set elm to its offsetParent
while(elm != null)
{
y = parseInt(y) + parseInt(elm.offsetTop);
elm = elm.offsetParent;
}
return y;
}
function Large(obj)
{
var imgbox=document.getElementById("imgbox");
imgbox.style.visibility='visible';
var img = document.createElement("img");
img.src=obj.src;
img.style.width='200px';
img.style.height='200px';
if(img.addEventListener){
img.addEventListener('mouseout',Out,false);
} else {
img.attachEvent('onmouseout',Out);
}
imgbox.innerHTML='';
imgbox.appendChild(img);
imgbox.style.left=(getElementLeft(obj)-50) +'px';
imgbox.style.top=(getElementTop(obj)-50) + 'px';
}
function Out()
{
document.getElementById("imgbox").style.visibility='hidden';
}
<img id='img1' src='images/Sample.jpg' onmouseover="Large(this)" />
注释
希望这个 JavaScript 能够解决你的弹出图像需求。如果你以其他方式实现了弹出图像功能,或者开发了一个功能更丰富的脚本,请放置一个指向你的 CodeProject 文章的链接,以便其他人也可以参考它。