使图片自适应屏幕大小的js

JavaScript016

使图片自适应屏幕大小的js,第1张

对小屏幕的人来说,经常有人发的图片超过你的屏幕大小,页面下面会出现一个横向滚动条,浏览起来很不方便,有的网站因为排版问题,导致一行文字过长,拉伸了整个页面,都可以通过这个脚本来“修正”,让该页面更适合你的屏幕大小。

gBrowser.loadURI("javascript:(function(){function%20t(f){a=d.createNodeIterator(d,1,f,false)while(a.nextNode()){}}var%20d=documentt(function(e){x=e.offsetLeftl=e.offsetParentwhile(l!=null){x+=l.offsetLeftl=l.offsetParent}var%20w=d.documentElement.clientWidth-xvar%20s=e.styleif(s.marginLeft)w-=s.marginLeftif(s.marginRight)w-=s.marginRightif(s.paddingLeft)w-=s.paddingLeftif(s.paddingRight)w-=s.paddingRightif(s.borderSize)w-=s.borderSizew-=d.defaultView.innerWidth-d.documentElement.offsetWidthif(e.tagName=='IMG'){h=e.clientHeight*w/e.clientWidths.maxHeight=h}s.maxWidth=w+'px'})})()")

在做网站的时候,往往图片的处理很重要,固定尺寸容易变形拉伸,不固定又会有不可预知的问题,有可能撑开页面。使用js和css将图片的现实控制在固定的区域内,大于这个区域的等比例缩放,小于这个区域的居中显示。

代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns=" http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/htmlcharset=utf-8" />

<title>css+js完美控制图片大小</title>

<script type="text/javascript" language="JavaScript">

<!--

var flag=false

function DrawImage(ImgD){

var image=new Image()

image.src=ImgD.src

if(image.width>0 &&image.height>0){

flag=true

if(image.width/image.height>= 400/400){

if(image.width>400){

ImgD.width=400

ImgD.height=(image.height*400)/image.width

}else{

ImgD.width=image.width

ImgD.height=image.height

}

ImgD.alt=image.width+"x"+image.height

}

else{

if(image.height>400){

ImgD.height=400

ImgD.width=(image.width*400)/image.height

}else{

ImgD.width=image.width

ImgD.height=image.height

}

ImgD.alt=image.width+"x"+image.height

}

}

}

//-->

</script>

<style type="text/css">

<!--

* {

margin:0

padding:0

}

li {

list-style:none

}

img {

border:0

}

.group_head {

width:400px

height:400px

line-height:400px

border:1px solid #ccc

overflow:hidden

position:relative

text-align:center

float:left

margin-right:10px

}

.group_head p {

position:static

+position:absolute

top:50%

vertical-align:middle

}

.group_head img {

position:static

+position:relative

top:-50%left:-50%

vertical-align:middle

}

-->

</style>

</head>

<body>

<ul class="jobGroup">

<li><a href="../group/index.php?group_id=10011"><div class="group_head"><p><img width="400" height="400" src=" http://www.baidu.com/img/baidu_logo.gif" onload="DrawImage(this)"/></p></div></a>

</li>

</ul>

</body>

</html> PS.本文来自: http://www.code-123.com/html/2009814191245580.html