jQuery Mobile Beta: 无法再使用$('[data-role=header]')了吗?

3

我曾经可以获得

$('[data-role=header]').first().height()

在使用jQuery 1.5.2版本时可以正常运行,但在使用jQuery 1.6.1版本的beta版时无法运行。是否有什么变化?

完整代码 - 这将向console.log写入0...

<!DOCTYPE html> 
<html> 
 <head> 
 <title>Page Title</title> 
 <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
 <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0b1/jquery.mobile-1.0b1.min.css" />
 <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
 <script type="text/javascript"
  src="http://code.jquery.com/mobile/1.0b1/jquery.mobile-1.0b1.min.js"></script>
 <script type="text/javascript">
 $(document).ready(function() {
 console.log($('[data-role=header]').first().height());
 });
 </script>
</head> 
<body> 
<div data-role="page" id="home">

       <div data-role="header">
       <h1>Header</h1>
       </div>
 <div data-role="content">
         //lots of code
        </div>
 </div>
 </body>
</html>

但是,将其更改为jQuery 1.5.2和jQuery Mobile alpha:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.2.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0a4/jquery.mobile-1.0a4.min.js"></script>

同时,它写入了标题div的非零高度。

顺便说一下,即使没有jQuery Mobile,使用jQuery 1.6.1时它也是非零的。因此,这与jQuery Mobile的渲染有关。

发布说明中没有发现任何暗示可能发生了什么,但我不是jQuery专家。


它在Alpha/Beta中写了什么,或者你期望它写什么? - Phill Pafford
在 Alpha 版本中,它会写入一些非零内容,因为 div 具有非零高度。在 Beta 版本中,它是零。顺便说一句,使用 jQuery 1.6.1 但没有使用 jQuery Mobile 时,它也是非零的(已编辑问题以反映此情况)。 - Richard
你能试试这个吗:$('[data-role="header"]').first()。height() - Phill Pafford
2个回答

3

导致差异的变化是“响应式设计助手类:现已弃用”

我们提供了一组响应式设计助手类,旨在轻松构建适应各种屏幕宽度的响应式设计。当时,我们采用了一种动态附加最小和最大宽度类到body上的系统,在加载、调整大小和方向更改事件中更新,作为解决Internet Explorer不支持媒体查询的限制的方法。

基本上,在beta版本中,页面会将min-height设置为当前页面高度,这会覆盖alpha版本中的.landscape { min-height: 300px; }

如果您需要更改页面布局,则看起来需要使用CSS媒体查询,或者如果您需要固定高度,则只需在标题中添加CSS style="height:43px"即可。

似乎当您查询 height() 时,页面还没有准备好。jQuery.mobile 没有 document.ready。它没有解释为什么 alpha 和 beta 之间存在差异,但我猜测代码路径发生了变化,从而暴露了这个问题。
将查询包装在不同的事件中,可以按预期返回高度。
$("div:jqmData(role='page')").live('pageshow',function(){
    console.log($('[data-role=header]').first().height());
});

我通过在Chrome控制台检查DOM元素的offsetHeight发现了这个问题,它是非零的,但正如您所报告的,height()始终报告为0。然后我创建了一个链接,当单击时输出高度,结果是非零的。然后我意识到height()在页面完全准备好之前被调用了。
相关 - jQuery mobile $(document).ready equivalent

2

看起来他们确实改变了一些语法,文档如下:

当通过jQuery Mobile数据属性查找元素时,请使用自定义选择器 :jqmData(),因为它会自动将命名空间数据属性合并到查找中,以便在使用时进行查找。例如,不要调用 $("div[data-role='page']"),而应该使用 $("div:jqmData(role='page')"),它在内部映射到 $("div[data-"+ $.mobile.ns +"role='page']"),无需强制手动连接命名空间到您的选择器中。

请尝试以下内容:

$("div:jqmData(role='header')").first().height()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接