2015-07-21 118 views
2

請看看下面的2個的jsfiddle例子:jQuery.width()被返回百分比寬度,而不是像素寬度

實施例編號1

第一個是純HTML和單個呼叫到Jquery寬度函數,然後返回像素所期望的寬度。
Demo with pure HTML

HTML

<body class="ui-mobile-viewport ui-overlay-a" data-pinterest-extension-installed="cr1.38.2" style="background-color: rgb(255, 182, 50);"> 
    <div data-role="page" data-theme="b" id="mailiPage" style=""> 
     <div id="mainDiv" data-role="content" class="ui-content" data-theme="b" style="text-align:center;background-color:#ffb632;background-image:none;height:100%"> 
      <div class="ui-grid-b"> 
       <div id="left" class="ui-block-a" style="width:5%;"></div> 
       <div id="center" class="ui-block-b" style="width:90%;"></div> 
       <div id="right" class="ui-block-c" style="width:5%;"></div>   
      </div> 
     </div> 
    </div>  
</body> 

JAVASCRIPT:

alert('this width of the center div is in pixels: ' + $('#center').width() + '\n'); 

例編號2

第二個例子包括用於動態編寫html的javascript,以及對寬度函數的調用,在這種情況下返回百分比值而不是像素寬度。
Demo with only Javascript

JAVASCRIPT:

var strPage = "" 
var leftSideColumnsWidth = 5; 
var rightSideColumnsWidth = 5; 
var centerColumnsWidth = 90; 
$("body").empty(); 
strPage = strPage + "<div data-role='page' data-theme='b' id='mailiPage' style=''>" 
strPage = strPage +  "<div id='mainDiv' data-role='content' class='ui-content' data-theme='b' style='text-align:center;background-color:#ffb632;background-image:none;height:100%'>" //padding-top: 56px;'>" 
strPage = strPage +   "<div class='ui-grid-b'>" 
strPage = strPage +    "<div id='left' class='ui-block-a' style='width:" + leftSideColumnsWidth + "%;'>" 
strPage = strPage +    "</div>" 
strPage = strPage +    "<div id='center' class='ui-block-b' style='width:" + centerColumnsWidth + "%;'>" 
strPage = strPage +    "</div>" 
strPage = strPage +    "<div id='right' class='ui-block-c' style='width:" + rightSideColumnsWidth + "%;'>" 
strPage = strPage +    "</div>" 
strPage = strPage +   "</div>" 
strPage = strPage +  "</div>" 
strPage = strPage + "</div>" 

$("body").append(strPage); 

alert('this width of the center div is not in pixels but in percentage: ' +$('#center').width()+'\n'); 

任何想法,爲什麼它deffer?

UPDATE:

在動力版本,如果你標示出它定義了JQM頁面,包括「數據角色=‘頁面’」第一個div,寬度函數將返回在像素值! ! 現在問題仍然是爲什麼?

回答

4

jQuery Mobile頁面,即帶有[data-role=page]的div元素最初是隱藏的。和隱藏的元素:

通過.width()報告的值是不能保證準確 當元件或它的父是隱藏的。要獲得準確的值, 確保在使用.width()之前該元素可見。 jQuery將 嘗試暫時顯示然後重新隱藏一個元素,以便 度量其尺寸,但這是不可靠的,並且(即使準確的話)會顯着影響頁面性能。這個 顯示和回放測量功能可能會在jQuery的未來版本 中刪除。

話雖如此,你可能想要look at this example,掛鉤頁面顯示事件,以確定頁面(因此,該元素)是否可見。

+0

是的,解釋是'.width()'調用在相應的元素被渲染之前運行,但是jquery mobile與什麼有關? – blgt

+1

@blgt由JavaScript創建的「頁面」由於jQuery mobile CSS而隱藏。 –

+0

謝謝薩爾曼。也很好的答案和解決方案。 – user2299401