一个JavaScript缩略图的小例子
一个JavaScript缩略图的小例子
昨晚由于项目中客户要求在页面缩略图中,当鼠标移到图片上时能在图片下动态显示一张按比例的大点的图片
,因为原来的缩略图太小了看不清,由于时间比较紧就自己写了一个,可以实现的小例子.......
效果不好,但是希望能给初学者一个思路(代码写的有点乱)
思路:
当用户鼠标移到图片上时动态创建一个DIV并取出IMG的SRC中的图片连接,并生成一个缩略图在鼠标下方
哈哈.......第一次写这个..大伙看了不要笑.....写的不好........
1///生成DIV
function CreateShowDiv(obj)
2
{
3
var divPWG,htmlImg,imgid;
4
htmlImg="<table align=\"center\" ><tr><td><img onLoad=\"SetImgAutoSize(this);\" src=\""+obj.src+"\" /></td></tr></table>";
5
divPWG=document.createElement("div");
6
divPWG.style.ZIndex=999;
7
divPWG.style.left=parseInt(obj.offsetLeft)+parseInt(obj.width)+10+"px";
8
divPWG.style.top=document.body.scrollTop+event.clientY+"px";
9
divPWG.innerHTML=htmlImg;
10
divPWG.style.position="absolute";
11
divPWG.style.color="#0000FF";
12
divPWG.style.display="block";
13
divPWG.id="WinKenDiv";
14
obj.style.cursor="hand";
15
document.body.appendChild(divPWG);
16
obj.onmouseout=function(e)
{if(document.getElementById(divPWG.id))
{document.getElementById(divPWG.id).parentNode.removeChild(document.getElementById(divPWG.id))};}
17
}
18
19
///生成缩略图
20
function SetImgAutoSize(obj)
21

{
22
var MaxWidth=500;//设置图片宽度界限
23
var MaxHeight=400;//设置图片高度界限
24
var HeightWidth=obj.offsetHeight/obj.offsetWidth;//设置高宽比
25
var WidthHeight=obj.offsetWidth/obj.offsetHeight;//设置宽高比
26
if(obj.readyState!="complete")return false;//确保图片完全加载
27
if(obj.offsetWidth>MaxWidth)
{
28
obj.width=MaxWidth;
29
obj.height=MaxWidth*HeightWidth;
30
}
31
if(obj.offsetHeight>MaxHeight)
{
32
obj.height=MaxHeight;
33
obj.width=MaxHeight*WidthHeight;
34
}
35
}
36

function CreateShowDiv(obj)
2

{3
var divPWG,htmlImg,imgid;4
htmlImg="<table align=\"center\" ><tr><td><img onLoad=\"SetImgAutoSize(this);\" src=\""+obj.src+"\" /></td></tr></table>";5
divPWG=document.createElement("div");6
divPWG.style.ZIndex=999;7
divPWG.style.left=parseInt(obj.offsetLeft)+parseInt(obj.width)+10+"px";8
divPWG.style.top=document.body.scrollTop+event.clientY+"px";9
divPWG.innerHTML=htmlImg;10
divPWG.style.position="absolute";11
divPWG.style.color="#0000FF"; 12
divPWG.style.display="block";13
divPWG.id="WinKenDiv";14
obj.style.cursor="hand";15
document.body.appendChild(divPWG);16

obj.onmouseout=function(e)
{if(document.getElementById(divPWG.id))
{document.getElementById(divPWG.id).parentNode.removeChild(document.getElementById(divPWG.id))};}17
}18
19
///生成缩略图20
function SetImgAutoSize(obj) 21


{ 22
var MaxWidth=500;//设置图片宽度界限 23
var MaxHeight=400;//设置图片高度界限 24
var HeightWidth=obj.offsetHeight/obj.offsetWidth;//设置高宽比 25
var WidthHeight=obj.offsetWidth/obj.offsetHeight;//设置宽高比 26
if(obj.readyState!="complete")return false;//确保图片完全加载 27

if(obj.offsetWidth>MaxWidth)
{ 28
obj.width=MaxWidth; 29
obj.height=MaxWidth*HeightWidth; 30
} 31

if(obj.offsetHeight>MaxHeight)
{ 32
obj.height=MaxHeight; 33
obj.width=MaxHeight*WidthHeight; 34
} 35
} 36

在HTML中使用
<img
class="i_upload_size" id="i_qk_btn2_one"
src=""name="" onMouseOver="CreateShowDiv(this)">
只要在元素的onMouseOver事中加入CreateShowDiv(this)
使用简单
.哈哈
.