javascript - 相对于另一个元素放置元素

标签 javascript jquery html css

首先,这是 fiddle 的链接:https://jsfiddle.net/ad7vmhs1/

我想将搜索按钮 $('#search-btn') 放在搜索框 $('#search-box') 旁边。我希望当导航栏展开时搜索框位于中心,所以我这样设置:

#search-btn {
  position: absolute;
}

但现在 search-btn 不在我想要的位置。我查找了一些将 $('#search-btn') 相对于 $('#search-box') 放置的代码,并得到如下内容:

window.pos = $('#search-box').position();
$('.navbar-toggler').on('click', function () {
    if (window.windowSize < 960) {
        $("#search-btn").css({
            position: "absolute",
            top: pos.top + "px",
            left: (pos.left + width + 10) + "px"
        })
    }
})

此代码似乎有效,只是当导航栏折叠时它无法正确捕获搜索框的位置。我怎样才能做到这一点?

期望的输出:

enter image description here

上图是我想要的 - 搜索框位于中心,搜索按钮位于其旁边。

如果我删除 $('#search-btn') 的“position:absolute”,则底部图像是输出。搜索框+搜索按钮的组合位于中心。

最佳答案

这里不需要 JavaScript。将搜索栏和搜索按钮放在同一个“公共(public)父元素”中,并只将搜索按钮设为position:absolute。搜索栏的大小将决定“公共(public)父元素”的大小,而搜索按钮将绝对定位,始终 float 到“公共(public)父元素”的一侧:

.menu {
  position: absolute;
  left: 0; top: 0;
  width: 100%;
}
.option {
  position: relative;
  width: 200px;
  height: 30px; line-height: 30px;
  /* margin-left = width / -2 */
  left: 50%; margin-left: -100px;
  text-align: center;
}
.option.search > .search-bar {
  /* margin-top = (30 - height) / 2 */
  width: 200px; height: 26px; margin-top: 2px;
  border: none;
  box-shadow: inset 0 0 0 1px #000000;
  text-align: center;
  font-size: 100%;
}
.option.search > .search-btn {
  position: absolute;
  left: 100%; top: 50%;
  margin-left: 10px;
  width: 60px;
  /* margin-top = height / -2 */
  height: 30px; line-height: 30px; margin-top: -15px;
  border-radius: 10px;
  box-shadow: inset 0 0 0 1px #00a000;
  color: #00a000;
}
<div class="menu">
  <div class="option">Option 1</div>
  <div class="option">Option 2</div>
  <div class="option">Option 3</div>
  <div class="option search">
    <input type="text" class="search-bar" placeholder="Search" />
    <div class="search-btn">Search</div>
  </div>
</div>

此布局应该适用于任何合理的情况。

关于javascript - 相对于另一个元素放置元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53919007/

相关文章:

javascript - 加入分割的 JSON-LD 数据?

javascript - 如何将秒转换为 HH :mm to HH:mm:ss in moment. js

javascript - 无法创建或清除消息警报

html - 如何使用 thymeleaf 在 Spring Boot 中加载图像?

jquery - 使用jQuery改变整个wordpress网站的CSS

javascript - 连接 html 元素后,结果变量返回 0

javascript - 使用嵌套 ng-repeat 和动态 ng-model 作为对象

javascript - 如何在没有 npm/webpack 的情况下从 HTML 文件导入 React 模块

javascript - jQuery iBox(灯箱克隆)和 IFRAMES

javascript - 扩展 jquery.css 函数以覆盖 !important 样式