【问题标题】:position div with auto width left of screen将具有自动宽度的 div 定位在屏幕左侧
【发布时间】:2022-01-24 04:42:06
【问题描述】:

注意:sn-p 中的这个 css 不完全等于我的设置(我在 body 中固定了 div),但在其他方面它的效果相同。我有自动宽度的 div(里面的文本),它从左侧打开。我想关闭它,使其向左动画到其全宽减去 50px。当屏幕宽度大于元素宽度时,这很好用,但是当它更小时,我的元素已经被压扁,所以当我在按钮点击时进行计算时,宽度不正确,当我动画出来时,它没有达到预期位置(因为它会随着向左的更多空间扩展至其自然宽度)。

我该如何解决这个问题?

var b = $('.b')

document.querySelector('#toggle').addEventListener('click', function() {



  var w = b.outerWidth(true),
    pos = w - 50
  console.log(w)

  b.stop().animate({
    'left': -pos + 'px'
  }, {
    duration: 350
  });

})
.a {
  border: 1px solid #333;
  width: 200px;
  position: relative;
}

.b {
  background: #ddd;
  max-width: 300px;
  padding: 50px;
  text-align: center;
  position: absolute;
}

#toggle {
  position: absolute;
  left: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="a">
  <div class="b">

    <div class="t">Lorem ipsum dolor sit amet</div>
    <div class="t">Ut laoreet hendrerit mi.</div>
    <div class="t">Lorem ipsum dolor sit amet</div>

  </div>
</div>

<a href="#" id="toggle">toggle</a>

【问题讨论】:

    标签: javascript html jquery css


    【解决方案1】:
    • 不要使用 jQuery
    • 使用 CSS 和 transform translatetransition 获得所需的动画
    • 使用 JavaScript Element.classList.toggle() 所需的 CSS 类 — 这会将元素从左 -100%(其自身宽度)转换为左 0%。
    • 如果您确实需要一个按钮,请使用&lt;button type="button"&gt;。锚点用于其他用途(导航)。

    const EL = (sel, par) => (par||document).querySelector(sel);
    
    EL("#toggle").addEventListener("click", () => {
      EL("#menu").classList.toggle("is-open");
    });
    /* QuickReset */
    * {
      margin: 0;
      box-sizing: border-box;
    }
    
    #toggle {
      position: fixed;
      right: 0;
      padding: 1rem;
      /* hopefully you know how to style a Button */
    }
    
    #menu {
      position: fixed;
      padding: 30px;
      width: calc(100vw - 100px); /* or whatever you want, does not matters */
      height: 100vh;
      background: gold;
      transition: transform 0.5s; /* transition property and duration */
      transform: translateX(-100%); /* -100% of self-width (hidden) */
    }
    
    #menu.is-open {
      transform: translateX(0%); /* (visible) */
    }
    <div id="menu">I am something that actually toggles</div>
    
    <button type="button" id="toggle">Toggle</button>

    【讨论】:

    • 对不起,但这不是我需要的。我虽然从演示和我的描述中很清楚。它需要动画到其全宽 - 50px。该元素没有固定宽度。如果它的自然宽度比父体宽,当它动画出来时,它会扩展,所以我不能正确计算左。在我的演示中,想象“.a”是 body 元素。
    • @Toniq 你不需要一个固定的宽度,上面仍然可以工作。它甚至在 CSS 注释中提到:“或任何你想要的,都无所谓”。而且我无法想象.abody,因为在这种情况下切换按钮将被放置在身体之外:)
    • 但是我如何让它关闭它的全宽减去 50px(所以它在关闭时伸出 50px),这是我的问题?编辑:我找到了:transform: translateX(calc(-100% + 50px));
    • @Toniq 确切地说, calc() 是您在这里处理任何动态 + 已知事物的朋友。
    猜你喜欢
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    • 2023-02-22
    • 2011-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多