You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Magento2移动端如何将div.sidebar.main移入products_list_toolbar?

解决方案

1. 移动端专属容器迁移(动态DOM调整)

若XML布局无法直接实现移动端专属的容器移动,推荐用JavaScript结合媒体查询动态调整DOM结构,避免干扰桌面端布局:

  • 在主题的catalog_category_view.xml中引入自定义脚本:
    <referenceContainer name="before.body.end">
        <block class="Magento\Framework\View\Element\Template" name="mobile.sidebar.mover" template="Magento_Theme::js/mobile-sidebar-move.phtml"/>
    </referenceContainer>
    
  • 创建mobile-sidebar-move.phtml文件,写入以下逻辑:
    require(['jquery'], function($) {
        function adjustSidebarPosition() {
            const $sidebar = $('.sidebar.main');
            const $toolbar = $('.products_list_toolbar');
            const $amount = $toolbar.find('.toolbar-amount');
            const $sorter = $toolbar.find('.sorter');
            const mobileBreakpoint = 768;
    
            if ($(window).width() < mobileBreakpoint) {
                if (!$sidebar.parent().is($toolbar)) {
                    $sidebar.insertAfter($amount).insertBefore($sorter);
                }
            } else {
                if ($sidebar.parent().is($toolbar)) {
                    // 替换为sidebar原父容器选择器,比如.page-main
                    $('.page-main').prepend($sidebar);
                }
            }
        }
    
        $(document).ready(adjustSidebarPosition);
        $(window).resize(adjustSidebarPosition);
    });
    
  • 注意:需根据实际页面结构调整容器选择器、断点宽度等参数。

2. 在toolbar.phtml中调用LayeredNavigation筛选器模板

直接修改主题下的Magento_Catalog/templates/product/list/toolbar.phtml,在toolbar-amount与sorter之间插入以下代码:

<div class="mobile-filter-wrap" style="display: none;">
    <?= $block->getLayout()->createBlock(\Magento\LayeredNavigation\Block\Navigation::class)
        ->setTemplate('Magento_LayeredNavigation::view.phtml')
        ->toHtml() ?>
</div>

再通过CSS媒体查询控制移动端显示:

@media (max-width: 767px) {
    .mobile-filter-wrap {
        display: block !important;
    }
    .sidebar.main {
        display: none;
    }
}

可选XML布局方案

若偏好XML实现,可在主题的catalog_category_view.xml中配置:

<referenceContainer name="sidebar.main" remove="true"/>
<referenceContainer name="products_list_toolbar">
    <block class="Magento\LayeredNavigation\Block\Navigation" name="mobile.layered.nav" template="Magento_LayeredNavigation::view.phtml" after="toolbar-amount" before="sorter">
        <arguments>
            <argument name="css_class" xsi:type="string">mobile-filter-wrap</argument>
        </arguments>
    </block>
</referenceContainer>

配合上述CSS媒体查询控制显示逻辑即可。

内容的提问来源于stack exchange,提问作者D.D.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 22:20:33