以下是网页中图片超过指定大小自动缩放,并且可以点击看大图的代码
[CODE=javascript] //改变图片大小 function resizeImg() { var contentwidth=565;//设置图片最大宽度 var imageAll=document.getElementById("con").getElementsByTagName("img");//con为图片所在层的ID var turewidth,tureheight; if (imageAll !=null) { for (i=0; iimageAll[i].width) { if(imageAll[i].height==tureheight) { imageAll[i].style.height=imageAll[i].height/turewidth*imageAll[i].width+"px"; } imageAll[i].onclick=function(){window.open(this.src)}; imageAll[i].style.cursor="pointer"; imageAll[i].title="点击查看原始尺寸:"+turewidth+"*"+tureheight+"px"; } else { imageAll[i].style.width=turewidth+"px"; } } } } if (window.addEventListener) window.addEventListener("load", resizeImg, false); else if (window.attachEvent) window.attachEvent("onload", resizeImg); else window.onload=resizeImg [/CODE]
经常有些JS代码明明在别人网页上可以运行,拷贝过来运行却出错,这个时候可以检查下是不是DOCTYPE声明的问题
在没有DOCTYPE声明的情况下:
document.body.clientWidth
document.body.clientHeight
为当前窗口的宽度/高度;
在DOCTYPE声明以后
document.body.clientWidth
document.body.clientHeight
为整个页面的宽度/高度;
document.documentElement.clientWidth
document.documentElement.clientHeight
为当前窗口的宽度/高度;
同样增加DOCTYPE声明后
document.body.scrollLeft
document.body.scrollTop
要改为
document.documentElement.scrollLeft
document.documentElement.scrollTop
网上搜索的一段代码,但是加上DOCTYPE后就不能用了,于是乎修改了一下,现在完美支持FF和IE
JS代码如下:
- var img = document.getElementById("img");
- var xPos = 20;
- var yPos = document.documentElement.clientWidth - img.offsetHeight;
- var step = 1;
- var delay = 5;
- var height = 0;
- var Hoffset = 0;
- var Woffset = 0;
- var yon = 0;
- var xon = 0;
- var pause = true;
- var interval;
- img.style.top = yPos + "px";
- function changePos() {
- width = document.documentElement.clientWidth;
- height = document.documentElement.clientHeight;
- Hoffset = img.offsetHeight;
- Woffset = img.offsetWidth;
- img.style.left = xPos + document.documentElement.scrollLeft + "px";
- img.style.top = yPos + document.documentElement.scrollTop + "px";
- if (yon) {
- yPos = yPos + step;
- } else {
- yPos = yPos - step;
- }
- if (yPos < 0) {
- yon = 1;
- yPos = 0;
- }
- if (yPos >= (height - Hoffset)) {
- yon = 0;
- yPos = (height - Hoffset);
- }
- if (xon) {
- xPos = xPos + step;
- }
- else {
- xPos = xPos - step;
- }
- if (xPos < 0) {
- xon = 1;
- xPos = 0;
- }
- if (xPos >= (width - Woffset)) {
- xon = 0;
- xPos = (width - Woffset);
- }
- }
- function start() {
- img.visibility = "visible";
- interval = setInterval(‘changePos()’, delay);
- }
- start();
最近评论