2016-11-25 114 views
1

我有dijit dialog,我需要根據圖像的大小設置對話框大小。獲取圖像大小並相應地設置div大小

爲了實現這一點,我需要在創建對話框之前加載圖像並從圖像中獲取屬性。 Image onload()方法沒有達到我的要求,因爲在創建對話框並將圖像放置在其上之前,我需要大小。任何人都可以告訴我一種解決此問題的方法嗎?

在此先感謝您的建議。

+0

你可以使用body.onload() – GraveyardQueen

+1

顯示你已經嘗試過。如果您在創建對話框之前需要大小,那麼在您的圖像上創建它,而不是在之前 –

+1

您可以加載圖像('var i = new Image(); i.src =「url」;'),等到它加載,然後創建對話框,然後將圖像添加到它。它被緩存,所以它會立即出現。 –

回答

0

圖像onload()方法未能滿足我的要求,因爲在創建對話框並將圖像放置在其上之前需要大小 。

三個步驟:

  1. 給圖像display: none默認的樣式表,以便它不顯示(或佔用任何空間)時,它加載。

  2. 當圖像加載時,javascript檢測到,然後運行函數來設置對話框大小。

  3. 使用javascript替換display:nonedisplay:blockdisplay:inline-block

0

在實例化對話框之前,您可以獲取圖像屬性。

注意,當窗口比它的寬度更少的,更大的dialog的dijit調整大小(所以你不能強迫一個固定的)

這裏是一個片段點擊 - >乳寧樣品

require(["dijit/Dialog","dijit/form/Button","dojo/domReady!"],function(Dialog,Button){ 
 
    
 
    var imageUrl = "https://cdn.elegantthemes.com/blog/wp-content/uploads/2015/02/custom-trackable-short-url-feature.png"; 
 
    
 
    var dialog 
 
    var image = new Image(); 
 
    
 
    // passing src image url to call onload function without add to dom 
 
    image.src = imageUrl; 
 

 
    image.onload = function(e) { 
 
    \t console.log(image.width); 
 
    console.log(image.height); 
 
    
 
    dialog = new Dialog({ 
 
     title: "My Dialog", 
 
     /* if you want to pass the image */ 
 
     content: "<img src='"+imageUrl+"' />", 
 
     style: "width:"+image.width+"px" 
 
    }); 
 
    } 
 
    
 
    var btn = new Button({ 
 
     label: "Show me !", 
 
     onClick: function(){ 
 
      dialog.show(); 
 
     } 
 
    }, "btn").startup(); 
 
\t 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script> 
 
<link href="https://ajax.googleapis.com/ajax/libs/dojo/1.6/dijit/themes/claro/claro.css" rel="stylesheet"/> 
 

 
<body class="claro"> 
 
    <div id="btn"></div> 
 
</body>
後全頁