2009-08-29 145 views
1

如何动态更改div的高度。如何动态更改div的高度

为什么这个不行:

var priceBarElement = $("priceBar"); 
priceBarElement.style.height = request.responseText+"px"; 

,我希望用改变并通过该行给出进一步下跌的priceBar股利。

<div id="priceBar" style="width:28px;margin-top:20px;background:#F00"></div> 

我得到了高度的正确值发送到页面上,我可以看到,因为我把它打印出来。但我似乎无法使用该值来更改priceBar div的高度。

我使用彗星发送“高度”,因此没有明确的行动要求一个新的“高度”。

<%@page contentType="text/html" pageEncoding="UTF-8"%> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd"> 

<%@page import="com.astheymove.util.ApplicationPathUtils"%><html> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <title>Comet Weather</title> 
    <script src="javascript/prototype.js" type="text/javascript"></script> 
    <script src="javascript/scriptaculous.js" type="text/javascript"></script> 

    <script type="text/javascript"> 
     function go(){ 
      var url = '<%= ApplicationPathUtils.getApplicationPath(pageContext) + "/prices" %>'; 
      var request = new XMLHttpRequest(); 
      request.open("GET", url, true); 
      request.setRequestHeader("Content-Type","application/x-javascript;"); 
      request.onreadystatechange = function() { 
       if (request.readyState == 4) { 
        if (request.status == 200){ 
         if (request.responseText) { 
          var forecastsElement = $("forecasts"); 
          forecastsElement.innerHTML = request.responseText; 
          var priceBarElement = $("priceBar"); 
          priceBarElement.style.height = request.responseText+"px"; 
          // highlight it 
          //new Effect.Highlight(forecastsElement, { startcolor: '#C0C0C0', 
          // endcolor: '#ffffff' }); 
         } 
        } 
        // not to highlight too often 
        //setTimeout("go();",1000); 
        go();         
       } 
      }; 
      request.send(null); 
     } 
    </script> 
</head> 
<body> 
    <h1>Rapid Fire Weather</h1> 
    <input type="button" onclick="go()" value="Go!"></input> 
    <div id="forecasts" style="padding:10px; border:1px solid #ccc; background:#ffffff;"> 
     Weather forecasts! 
    </div> 
    <div id="pricesPanel" style="height:100px;"> 
       <div id="priceBar" style="width:28px;margin-top:20px;background:#F00"></div> 
    </div> 
</body> 
</html> 
+0

如果任何人都可以帮助我用jQuery来做到这一点,那将是理想的选择。 – Ankur 2009-08-29 17:02:27

回答

1

您正在尝试设置节点的高度之前DOM已准备就绪。处理XHR时有时会很棘手,因为您想立即调用XHR,但有时在页面加载之前会发生回调。最初,将XHR函数放入window.onload函数(或Prototype DOM Ready等价物)中。如果解决了这个问题,你可以先尝试XHR,并测试DOM是否准备好 - 如果没有,则设置它,推迟函数。

1

试试这个:

var priceBarElement = $("#priceBar")[0]; 
priceBarElement.style.height = request.responseText+"px"; 
0

甚至更​​简洁:

$('priceBar').setStyle({height: request.responseText+"px"});