前段时间做项目,要实现,一张图片,鼠标放上去图片自动变大的效果,虽然难度不大,但当时也想了一段时间,当时没时间记录一下,现在有时间了,写篇博客把代码给记录一下;
效果如下:
代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <style> #demo{overflow:hidden;width:120px;text-align:center;padding:10px;} #demo img{border:none;width:100px;height:100px;border:5px solid #f4f4f4} #enlarge_images{position:absolute;display:none;z-index:2;border:5px solid #f4f4f4} </style> </head> <body> <div id="demo"> <img src="pic.png"> </div> <div id="enlarge_images"></div> <script> var demo = document.getElementById("demo"); var images = demo.getElementsByTagName("img"); var large_image = document.getElementById("enlarge_images"); for(i=0; i<images.length; i++) { var temp = images[i]; temp.onmousemove = function(event) { event = event || window.event; large_image.style.display = "block"; large_image.innerHTML = '<img src="' + this.src + '" />'; large_image.style.top = document.body.scrollTop + event.clientY + 10 + "px"; large_image.style.left = document.body.scrollLeft + event.clientX + 10 + "px"; } temp.onmouseout = function() { large_image.innerHTML = ""; large_image.style.display = "none"; } temp.onclick = function() { window.open( this.src); } } </script> </body> </html>
注:
a)两个div,一个用于显示小图片,另一个用于显示大图片;
b)JS,当鼠标移动到上面时,设置第二个div的显示内容及显示位置;
c)需注意的是,large_image的display在none和block之间转化,是为了鼠标,多次放到图片上时的情况;