【问题标题】:Move form element outside the form, and place it inside another div将表单元素移到表单之外,并将其放置在另一个 div 中
【发布时间】:2021-10-09 01:29:39
【问题描述】:

我的页面上有一个带有搜索/过滤器表单的侧边栏。我试图做的是从这个表单中移动一个元素(排序顺序下拉菜单),使用 CSS/JS 将其显示在表单之外,并将其显示在右侧的 div 中。在不丢失表单功能的情况下是否有可能?请检查我的代码:

<div class="left-sidebar">
  <form>
    <div class="move-this-outside">Dropdown is here</div>
  </form>
</div>
<div class="page-content">
  <div class="sort-order-container">Here i need to drop it</div>
</div>

当然我可以使用position:absolute;,但是如何使这个下拉列表相对于表单外的另一个div?页面内容灵活(分页、横幅等)。它必须在物理上位于&lt;form&gt;&lt;/form&gt; 内才能工作,但我需要在另一个 div 中显示(模拟显示)它。

【问题讨论】:

  • 您可以使用form attribute将表单元素与特定表单相关联
  • 但在这种情况下我无权修改 html。
  • 嗯?为什么不?您可以修改 CSS 但不能修改 HTML?这是一个奇怪的情况,真的没有多大意义......你要么正在开发应用程序,要么你没有。您不能单独更改 HTML/JS/CSS,它们是相互依赖的,尤其是 HTML 和 CSS。如果您无权进行更改,那么这个问题毫无意义。
  • 我的意思是我猜你可以在页面加载后使用一些 JS 来移动它,并为其添加 form 属性,但这是一个荒谬的解决方法,不应该必要的。只需更改 HTML。如果你因为一些奇怪的原因不被允许,那么让负责它的人来改变它。
  • 过滤表单是一个WordPress插件,我不能修改这部分。

标签: javascript php html jquery css


【解决方案1】:

假设您能够运行 Javascript 而没有与编辑表单的 HTML 相同的限制,那么像这样一些非常简单的 Javascript 应该足以将 select 菜单移动到新位置。

我将相关代码放在setTimeout 中,只是为了让move 可以观察到。

setTimeout(()=>{
  /* identify the various HTML elements needed in the move process */
  let form=document.querySelector('.left-sidebar > form');
  let target=document.querySelector('.page-content > .sort-order-container');

  /* Move the Select from original location (sidebar) to the new location */
  target.appendChild( form.querySelector('.move-this-outside') );

  /* set the ID of the form and associate the select with that form by ID */
  form.setAttribute('id','filter');
  target.firstElementChild.querySelector('select').setAttribute('form','filter');
},2500);
/*
  To show the select has moved
*/
.left-sidebar{border:1px solid red;}
.page-content{border:1px solid black;}
.sort-order-container{border:1px solid blue;}
select{background:pink}
h1{font-size:1.1rem}
*{padding:0.25rem;margin:0.25rem auto}
<div class="left-sidebar">
  <form>
    <h1>Select Menu was here</h1>
    <!-- source -->
    <div class="move-this-outside">
      <select>
        <option>Hello World
        <option>Goodbye World
      </select>
    </div>
  </form>
</div>
<!--

  other html content perhaps

-->
<div class="page-content">
  <div class="sort-order-container">
  <!-- target -->
  </div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-06
    相关资源
    最近更新 更多