【问题标题】:jQuery on resize, clone div, detach and append againjQuery 调整大小、克隆 div、分离并再次附加
【发布时间】:2014-12-02 14:40:46
【问题描述】:

我正在开发一个完整的响应式网站,但我遇到了一件事情 - 也许你可以帮助我。

基本结构:

<div id="content">
<div id="content_left"></div><!--end content_left-->

<div id="content_right">
<div class="profile_box"></div><!--end profile_box-->
</div><!--end content_right-->

</div><!--end content-->

我正在尝试做这些事情:

  • (当我将网站缩小到 600 像素或更少时)
    • 克隆整个#content_right
    • 将 .profile_box 从 #content_right 移动到 #content_left
    • 分离整个#content_right
  • (当我将站点扩展到 600 或更多时)

    • 将#content_right 附加到#content
    • 将 .profile_box 移回原处 (#content_right)

    $(window).resize(function(){ if($('body').width()

它以一种方式工作 - 当我缩小网站时,.profile_box 被移动到 #content_left,整个 #content_right 被分离 - 所以它工作得很好,但是......

另一方面,有一个问题。当我在“缩小”网站并想要拉伸到 600 或更多时,#content_right 没有显示(在网站刷新后它会显示,但我想在不刷新的情况下显示它)。

它可以在移动设备上运行,因此,当用户旋转手机时,我想“飞行”工作取决于屏幕宽度。

任何帮助将不胜感激 - 谢谢。

我不想隐藏或显示它,因为即使它被隐藏了,它仍在加载数据。

【问题讨论】:

  • 这看起来非常复杂。为什么不简单地使用 appendTo() 将元素从一个 div 移动到另一个,然后返回原位? stackoverflow.com/questions/1279957/… 此外,$(window).resize() 方法大约在每个调整大小的像素处触发,这意味着如果您将窗口大小调整 300 像素,您的操作将被触发 300 次。您应该将您的操作放在一个函数中,并在window.resize() 中进行测试,如果 body 小于或大于 600px,调用您的函数一次
  • 这会更容易,但在#content_right 我还有很多其他的东西,如果屏幕尺寸为 600 像素或更小,我不想加载它们。而且我不想浪费用户带宽来加载无论如何都会隐藏的东西(在小屏幕上)。你的意思是这样的: $(window).on("resize load", function () { $(body).resize(function(){ } }); ?我不擅长 jquery 脚本,如果它完全不同的话请举个例子。

标签: jquery responsive-design resize prepend detach


【解决方案1】:

您的 cr_clone 不存在于 else 语句中:

var cr_clone = $('#content_right').clone(true);
if($('body').width() < 600) {
            $("#content_right .profile_box").detach().prependTo('#content_left')
    $("#content_right").detach();
}
else{
    cr_clone.appendTo('#content');
}

更新

你需要两个 if 语句。仅当该部分尚不存在时,您才必须添加它:

var cr_clone = $('#content_right').clone(true);
if($('body').width() < 600) {
    if ($("#content_left #content_right").length == 0){
        $("#content_right .profile_box").detach().prependTo('#content_left');
        $("#content_right").detach();
    }

}
else{
    if ($("#content_left #content_right").length > 0) {
        cr_clone.appendTo('#content'); 
        $("#content_left profile_box").detach().prependTo('#content_right'); 
    }

}

【讨论】:

  • else{ cr_clone.appendTo('#content'); $("#content_left profile_box").detach().prependTo('#content_right'); } });现在,它正在将 .profile_box 移动到 #content_left 但多次(大约 25 o_O),当我拉伸站点时 #content_right 再次放置但 25 倍,并且没有其他 div 之前放置在 #content_right 中。大约有 25 个#content_right div,每个都有 .profile_box。无论如何感谢马修的快速回答。
  • 我认为你有 25 次,因为 window.rezise 事件会为你调整的每个 px 执行。因此,在附加之前,请确保它不存在。在
  • 你的意思是这样的: if($('body').width()
猜你喜欢
  • 1970-01-01
  • 2018-06-15
  • 2012-02-01
  • 1970-01-01
  • 2017-08-06
  • 1970-01-01
  • 2016-12-30
  • 2018-01-10
  • 2012-12-02
相关资源
最近更新 更多