0

I have a table like this:

<table>
<tr>
<td id='tdleftcontent' style='border:1px solid red;'>
    <asp:Label ID='lbl' runat="server"></asp:Label>
</td>
</tr>
</table>

With control lbl, in code behind, I set text as 'img src='/CMS/Images/News/event1.JPG' border='0' />'

    protected void Page_Load(object sender, EventArgs e)
    {
        this.lbl.Text = "<img alt='' src='/CMS/Images/News/event1.JPG' border='0' />";
    }

And in Javascript, I have a function to get HEIGHT of this td:

<script type="text/javascript">
$(document).ready(function(){
    var h = document.getElementById('tdleftcontent').offsetHeight;
    alert(h);
});

But the result is: h=22px. It mean the image does not show up on web yet. result picture: http://upanh.nguoihoian.info/di-534E.jpg

Please help me in solve this problem. Thank you very much.

4

4 に答える 4

0

次のように画像コントロールを使用することをお勧めします。

<asp:image runat="server" ImageUrl="~/CMS/Images/News/event1.JPG" BorderWidth="0" />

JavaScriptの場合は、jQueryの高さ関数を使用して高さを取得するだけです。

<script type="text/javascript">
$(window).load(function(){
    var h = $('#tdleftcontent').height();
    alert(h);
});
<script>

より具体的なニーズのために、jQueryにはinnerHeight関数とouterHeight関数もあります。

編集済み:他の人は、画像が読み込まれるまで高さの値が使用できないという良い点を示しています。ページ上のすべてが読み込まれるまで待ちたくない場合は、画像クライアント側を作成して、その読み込みイベントにアタッチできます。画像がDOMに追加された後、src属性を設定するように注意してください。

.NETコード

this.lbl.Attributes["data-src"] = "/CMS/Images/News/event1.JPG";

JavaScript

<script type="text/javascript">
$(document).ready(function(){
    var $td = $('#tdleftcontent');
    $('<img border="0" />')
        .bind('load', function() {
            $td.height();
            alert(h);
        })
        .bind('error', function() {
            $(this).hide();
        })
        .appendTo($td)
        .attr('src', $td.find('span').data('src'));
});
<script>
于 2012-04-17T05:36:34.463 に答える
0

ここでは使用$(document).readyしないでください。DOMの準備ができたらハンドラーを実行します。つまり、通常、画像は読み込まれません。代わりに使用$(window).loadするか、イメージ自体にロード ハンドラーを登録することをお勧めします。

于 2012-04-17T05:46:10.697 に答える
0

<asp:placeholder>の代わりに を使用してみて<asp:label>ください。ブラウザでソースを表示して、IMG タグが適切に作成され、SRC 属性が実際に存在することを確認してください。

于 2012-04-17T04:55:11.100 に答える
0

$(document).ready()DOM の準備が整うとコードが実行されることに注意してください。画像がロードされた後にコードを実行したい場合は、$(window).load(function () {})

于 2012-04-17T05:59:28.660 に答える