首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

兼容IE,firefox,chrome图片缩放效能

2012-10-23 
兼容IE,firefox,chrome图片缩放功能!DOCTYPE htmlhtml langenheadmeta charsetutf-8title

兼容IE,firefox,chrome图片缩放功能
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Image Zoom</title>

<style>
*{
margin:0;
padding:0;
font-size:0;
}
body{
background:#000;
}
/* view image */
img{
display:block;
}
.zoomout{
cursor:url(images/zoomout.cur), auto;
}
.zoomin{
cursor:url(images/zoomin.cur), auto;
}


</style>
<script type="text/javascript" src="js/jquery-1.5.min.js"></script>
<script type="text/javascript">

//<![CDATA[
jQuery(function(){
var isCanZoomed = false;//图片是否可以被缩放
/*
jQ_img 加载的img对象
imgH 图片实际高度
imgW 图片实际宽度
winH 窗口的高度
winW 窗口的宽度
pre  imgH / imgW 的比例;
*/
var jQ_img,imgH, imgW, winH, winW, pre;

//预加载图片
function loadImage(url, callback){
  var img = new Image();
  img.src = url;
  if(img.complete){
  callback.call(img);
  return;
  }
  img.onload = function (){
  callback.call(img);
  this.onload = null;
  };
}

//更新图片的高度和宽度
function updateCss(theClass, attribute, value){
var cssRules;
if(document.all){
cssRules = 'rules';
}else if(document.getElementById){
cssRules = 'cssRules';
}
for(var S = 0, len = document.styleSheets.length; S < len; S++){
var allRules = document.styleSheets[S][cssRules];
for(var R = 0,len2 = allRules.length; R < len2; R++){
var updateAttr = allRules[R];
if(updateAttr.selectorText == theClass){
updateAttr.style[attribute] = value;
}
}
}
}

//初始化图片
function initImage(){
imgH = this.height;
imgW = this.width;
pre = imgH / imgW;
$('body').append(this);
jQ_img = $(this);
updateCss('.zoomout', 'height', imgH+'px');
updateCss('.zoomout', 'width', imgW+'px');
jQ_img.addClass('zoomin');
setImageSize();
$(window).resize(setImageSize);
}

//设置图片的大小
function setImageSize(){
var outH = imgH,
outW = imgW;
$('html').css({
overflow: 'hidden'
});
winH = $(window).height();
winW = $(window).width();
$('html').css({
overflow: 'auto'
});

if(imgH > winH) {
outH = winH;
outW = outH / pre;
}
if(outW > winW) {
outW = winW;
outH = outW * pre;
}
updateCss('.zoomin', 'height', outH+'px');
updateCss('.zoomin', 'width', outW+'px');
getImageZoom();
}

//图片是否可以被缩放
function getImageZoom(){
if(imgH >= winH){
isCanZoomed = true;
}else if(imgW >= winW){
isCanZoomed = true;
}else{
isCanZoomed = false;
jQ_img.removeClass();
}
if(isCanZoomed){
if(!jQ_img.hasClass('zoomin')){
jQ_img.addClass('zoomout');
}
jQ_img.unbind('click').bind('click', function(){
jQ_img.toggleClass('zoomin');
jQ_img.toggleClass('zoomout');
});
}else{
jQ_img.unbind('click');
}
}

loadImage('images/003.jpg', initImage);

});
//]]>
</script>
</head>

<body>
</body>
</html>

热点排行