請看看下面的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,寬度函數將返回在像素值! ! 現在問題仍然是爲什麼?
是的,解釋是'.width()'調用在相應的元素被渲染之前運行,但是jquery mobile與什麼有關? – blgt
@blgt由JavaScript創建的「頁面」由於jQuery mobile CSS而隱藏。 –
謝謝薩爾曼。也很好的答案和解決方案。 – user2299401