QQ 1640076782

2009年09月25日

window.open弹出窗口自适应图片的大小(兼容多种浏览器)

Filed under: 网站程序OSC — past @ 4:45 下午

如何让弹出窗口自适应图片的大小
解决思路
主要思路是用window.open()方法打开一个窗口,然后再根据图片的大小resizeTo()窗口大小,必要时再用moveTo()方法调整窗口位置。现在问题在于如何获取图片的大小。
具体步骤
images对象,只要设置图片源src后就可以用document.images[0].width和document.images[0].height获取图片的宽和高,不过要注意,要把窗口边框、标题栏高度和图片距边界的距离计算在内。
代码如下(popup_image.php):

<script language=”javascript” type=”text/javascript”><!–
var i=0;

function resize() {

if (window.navigator.userAgent.indexOf(‘MSIE 6.0′) != -1 && window.navigator.userAgent.indexOf(‘SV1′) != -1) {
i=23; //IE 6.x on Windows XP SP2
} else if (window.navigator.userAgent.indexOf(‘MSIE 6.0′) != -1) {
i=50; //IE 6.x somewhere else
} else if (window.navigator.userAgent.indexOf(‘MSIE 7.0′) != -1) {
i=0;  //IE 7.x
} else if (window.navigator.userAgent.indexOf(‘MSIE 8.0′) != -1) {
i=0;  //IE 8.x
} else if (window.navigator.userAgent.indexOf(‘Firefox’) != -1 && window.navigator.userAgent.indexOf(“Windows”) != -1) {
i=0; //Firefox on Windows
} else if (window.navigator.userAgent.indexOf(‘Mozilla’) != -1 && window.navigator.userAgent.indexOf(“Windows”) != -1 && window.navigator.userAgent.indexOf(“MSIE”) == -1) {
i=45; //Mozilla on Windows, but not IE7
} else if (window.opera && document.childNodes) {
i=50; //Opera 7+
} else if (navigator.vendor == ‘KDE’ && window.navigator.userAgent.indexOf(“Konqueror”) != -1) {
i=-4; //Konqueror- this works ok with small images but not so great with large ones
//if you tweak it make sure i remains negative
} else {
i=70; //All other browsers
}

if (document.images[0]) {
imgHeight = document.images[0].height+235-i;
imgWidth = document.images[0].width+50;
var height = screen.height;
var width = screen.width;
var leftpos = width / 2 – imgWidth / 2;
var toppos = height / 2 – imgHeight / 2 +50;
window.moveTo(leftpos, toppos);
window.resizeTo(imgWidth, imgHeight);
}

self.focus();

}
//–></script>

在body加载函数:

<body onload=”resize();”>

下面为效果图:

Screenshot