使用Javascript动态更改div的宽度

时间:2011-10-30 04:41:54

标签: javascript

Here是测试网站。

我正在使用Javascript onClick事件函数来动态更改显示的全尺寸图像的src。但是,在更改包含图像的div的宽度时,这并不是完全相同的方式。我已经测试过该函数实际上是获得给定的宽度而且它是,所以它可能只是没有正确定义我的div的宽度值。

<?php
$username = $_GET['username'];
session_start();
$_SESSION['username'] = $username;

//Database Information
$dbhost = "";
$dbname = "";
$dbuser = "";
$dbpass = "";

//Connect to database
mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect:         ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());

//Do the query
$query = mysql_query("SELECT * FROM images ORDER BY idnum DESC LIMIT 5");

//Generate an array of all images
$images = array();
while($image = mysql_fetch_array($query)) {
//this adds each image to the images array
$images[] = $image;
$image['filename'] = $firstimage;
}
?>

<?php

// Beginning attempt at a caption script.



?>

<html>
<head>
<title>Home - Site in Development</title>
<link rel="stylesheet" type="text/css" href="styles.css"/>
 <script type="text/javascript">

 // Switches the url to view large image.

   function switchImageUrl(url, width) {
    document.getElementById('img-frame').src = url;
    document.GetElementById('center_frame').offsetwidth = width;

   }

 </script>



</head>
<body onLoad="CalculateAllImageWidthes()">
<div id='account_links'>
  <?php
  if ($_SESSION['username']) {
    echo "Welcome $username!";
  } else { ?>
    <a href='login.php'>Login</a> | <a href='register.php'>Register</a>
  <?php } ?>
   </div>

<h1>Picture Captions</h1>
<br/>
<br/>
<div id="left_bar">
  Submit a picture <a href="upload.php">here</a>.
<hr/>
<h2>Top Images</h2>
<br/>

<div id="front_pg_images">
  <?php foreach($images as $image) { ?>
    <a href="#" onClick="switchImageUrl('<?php echo $image['filename']; ?>', '<?php echo $image['width']; ?>')"><img src="<?php echo $image['filename'];?>" width="72px" height="58px" id="front_pg_thumbnail"/></a>
    <?php echo $image['name']." - by ".$image['submitter']; ?> <br/>
    <br/>
  <?php } ?>
 </div>
 </div>
 <div id="center_frame" width="<?php echo $image['width']; ?>">
  <img src="<?php echo $image['filename'];?>" name="default" id="img-frame" align="left" valign="top">
</div>

2 个答案:

答案 0 :(得分:4)

这是有问题的一行:

document.GetElementById('center_frame').offsetwidth = width;
  1. 方法的正确名称为getElementById - JavaScript区分大小写
  2. 使用offsetwidth
  3. 替换offsetWidth(无论如何应该是style.width
  4. width替换为width + 'px'
  5. 所以你的行看起来像:

    document.getElementById('center_frame').style.width = width + 'px';
    

答案 1 :(得分:0)

而不是.offsetwidth = width使用.style.width = width;