简体   繁体   English

在jquery-mobile中计算(不是CSS)width()

[英]Getting computed (not CSS) width() in jquery-mobile

I have a div id="XYZ" with CSS specified width: 37%; 我有一个div id =“ XYZ”,其CSS指定宽度为:37%;

I then wish to use the px width of this div to set other widths, but I can only access the given css% value and not the computed px width of the div in the DOM. 然后,我希望使用该div的px宽度设置其他宽度,但是我只能访问给定的css%值,而不能访问DOM中div的计算所得的px宽度。 What am I doing wrong? 我究竟做错了什么?

$( document ).on( "pagecreate", "#page", function( event ) {

        var divWidth = $("#XYZ").width();
        console.log('div XYZ width is ' + divWidth); 

});

It outputs 37. Which is the css % value, but jquery width() SHOULD give me the computed width in px, shouldn-t it? 它输出37。哪个是css%值,但是jquery width()应该以px为单位给我计算宽度,不是吗?

I was thinking that maybe the problem is that Im asking at 'pagecreate' (same result in deprecated 'pageinit'). 我在想,也许问题出在我问“ pagecreate”(导致“ pageinit”弃用的相同结果)。

How can I get the computed width of the div? 如何获得div的计算宽度?

Using pagecreate to retrieve actual .width() , .height() , .offest() , etc., won't return the computed value since page and elements within it are are all hidden. 使用pagecreate检索实际的.width() .height() .offest()等不会返回计算值,因为页面和其中的元素都被隐藏了。

To retrieve such data, you need to use pagecontainertransition when transition between previous page and next page is complete, or pagecontainerhide when previous page is completely hidden, or pagecontainershow when next page is completely visible. 要获取这样的数据,你需要使用pagecontainertransition当上页和下一页之间的过渡完成后,或pagecontainerhide当上一个页面是完全隐藏,或pagecontainershow当下一页是完全可见。

However, note that those events can't be attached to a specific page. 但是,请注意,这些事件不能附加到特定页面。 As of jQM 1.4, "page events" are replaced with " PageContainer Events ". 从jQM 1.4开始,“页面事件”被“ PageContainer事件 ”替换。 Thus, - unfortunately - you ought to use if statement or switch/case . 因此, 不幸的是 ,您应该使用if语句或switch/case

$( document ).on( "pagecontainershow" , function( event, ui ) {
  var divWidth = $( "#XYZ" ).width();
  console.log('div XYZ width is ' + divWidth);
});

You can use getComputedStyle 您可以使用getComputedStyle

The Window.getComputedStyle() method gives the values of all the CSS properties of an element after applying the active stylesheets and resolving any basic computation those values may contain. 在应用活动样式表并解决这些值可能包含的所有基本计算之后,Window.getComputedStyle()方法给出元素的所有CSS属性的值。

Use 采用

var divWidth = document.defaultView.getComputedStyle($("#XYZ")[0], null).width;

Or 要么

var divWidth = window.getComputedStyle($("#XYZ")[0], null).width;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM