当前位置: 首页 > 图文教程 > 网络编程 > Javascript > 利用onresize使得div可以随着屏幕大小而自适应的代码

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 利用onresize使得div可以随着屏幕大小而自适应的代码


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2010-01-20   浏览: 351 ::
收藏到网摘: n/a

javascript 利用onresize使得div可以随着屏幕大小而自适应的代码 当我们让div居中时候,一般有两种方法,一种是固定左右宽度,也就是使用像素绝对定位;另一种是用百分比来相对定位,在这种两种方式下,绝对定位是不能让div随着屏幕而自适应的,而用百分比就可以,但是,是用百分比就会有一个新的问题,如果我们的页面中有这么一句
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
的时候,top的百分比将会失效,而删除这句话的时候,一切正常,都是不知道这句标准的声明为什么会带来如此的不便
针对这个问题,我使用的下面的方法来实现div的自适应
首先 我用的是绝对定位的方式,先设置好div的左右上下边距。在body中添加两个事件,
<body bgcolor="#666666" onresize="test()" onload="getwah()">
getwah()用来获取屏幕的大小和div的各个边距,并计算出它们的差
复制代码 代码如下:

var height,width,width_cha1,width_cha2;
function getwah()
{
if(document.documentElement && document.documentElement.clientWidth)
{d_width = document.documentElement.clientWidth;}
else if(document.body)
{d_width = document.body.clientWidth;}
width=parseInt(d_width);
width_cha1=width-parseInt(document.getElementById("backi").style.left)
width_cha2=width-parseInt(document.getElementById("massage_box").style.left)
}

当屏幕大小变化的时候(onresize)触发test()函数,该函数就是用户根据之前获得屏幕与边距的差值重新设置div的边距,这样就可以实现党屏幕的大小改变后,div的边距也会相应地改变,从而实现div可以随着屏幕大小的改变而自适应
复制代码 代码如下:

function test()
{
if(document.documentElement && document.documentElement.clientWidth)
{d_width = document.documentElement.clientWidth;}
else if(document.body)
{d_width = document.body.clientWidth;}
var now_left1=parseInt(d_width )-width_cha1;
var now_left2=parseInt(d_width )-width_cha2;
document.getElementById("backi").style.left=now_left1
document.getElementById("massage_box").style.left=now_left2
}