我目前的代码是
<div id="column-left">
Test
</div>
当窗口大小小于640px时,如何将其更改为:
<div data-role="panel" id="left-panel" data-position="left">
Test
</div>
data-role =“panel”是jquerymobile代码。问题是关注我们如何将data-role =“panel”属性添加到div中。谢谢!
您可以在http://jsbin.com/wakagumu/11/edit中测试您的代码。如果成功,将id =“column-left”更改为data-role =“panel”id =“left-panel”后,测试“FIRST”将消失。
答案 0 :(得分:0)
$(window).resize(function(){
if ($(this).width() < 640) {
var myDiv = $('#column-left');
if (myDiv.length > 0) {
myDiv.attr('id', 'left-panel').data('role', 'panel').data('position', 'left');
}
} else {
var myDiv = $('#left-panel');
if (myDiv.length > 0) {
myDiv.attr('id', 'column-left').data('role', '').data('position', '');
}
}
});
答案 1 :(得分:0)
更改属性不会将div转换为面板,您需要手动初始化。在jQuery Mobile 1.3中,您应该在动态添加面板时使用.trigger("pagecreate")
,以便初始化。
以下解决方案创建面板,并在 page 的宽度较小时移动内容 div的元素;并删除面板并将 content div的元素返回到原始位置。此外,它会在标题中创建一个按钮以打开面板。它可用于任何页面事件以及窗口throttledresize
和orientationchange
。
$(window).on("throttledresize", function () {
var activePage = $.mobile.activePage;
if ($(window).width() < 500 && activePage.find("[data-role=panel]").length === 0) {
/* create button */
var button = $("<a/>", {
"data-role": "button",
"data-icon": "bars",
"id": "panelBtn",
"data-theme": "e",
class: "ui-btn-left"
}).text("Panel");
/* add click listener to open panel
and append it to header */
activePage.find(".ui-header").append($(button).on("click", function () {
$("#left-panel").panel("open");
}));
/* save menu */
var menu = $("#menu");
/* create a panel
append menu
create page */
activePage.prepend($("<div/>", {
id: "left-panel",
"data-role": "panel",
"data-position": "left",
"data-display": "push"
}).append($("<div/>", {
class: "ui-panel-inner"
}).append(menu))).trigger("pagecreate");
}
if ($(window).width() > 500 && activePage.find("[data-role=panel]").length === 1) {
/* remove panel and button
return menu to content div */
if (activePage.hasClass("ui-page-panel-open")) {
activePage.find("[data-role=panel]").panel("close").on("panelclose", function () {
var menu1 = activePage.find("[data-role=panel] #menu");
activePage.find("[data-role=content]").append(menu1);
activePage.find("[data-role=panel]").remove();
activePage.find("#panelBtn").remove();
activePage.trigger("pagecreate");
});
} else {
var menu1 = activePage.find("[data-role=panel] #menu");
activePage.find("[data-role=content]").append(menu1);
activePage.find("[data-role=panel]").remove();
activePage.find("#panelBtn").remove();
activePage.trigger("pagecreate");
}
}
});
<强> Demo 强>