【问题标题】:Is there anyway to detect the margin of a div?反正有没有检测到一个div的边距?
【发布时间】:2021-12-07 18:02:40
【问题描述】:

我想知道 div1 的左边距,所以我可以在我的代码中使用它。以这种方式设置,左侧的边距将根据屏幕大小而变化。如何检测这个 div 的左边距?

<div class="max-w-6xl m-auto">
</div>

【问题讨论】:

    标签: reactjs tailwind-css


    【解决方案1】:

    在 react 中,您可以使用 ref 回调,它接收 HTML DOM 元素作为参数。在此回调中,您可以从元素中查询margin-left 样式并将其存储在一个状态中。这是一个例子:

    const App = () => {
      const [marginLeft, setMarginLeft] = useState(0); // in pixels
    
      const retrieveMargin = (elm) => {
        if (elm != null) {
          let styles = window.getComputedStyle(elm);
          let ml = styles.getPropertyValue("margin-left");
          setMarginLeft(Number.parseInt(ml.replace("px", "")));
        }
      };
    
      return <div class="mydiv" ref={retrieveMargin}></div>;
    };
    

    【讨论】:

    • 这行得通,如果用户不断改变屏幕尺寸怎么办。有没有办法更新marginLeft,而无需刷新?
    • 在这种情况下,您必须使用useRef 设置一个钩子并让retrieveMargin 使用该特定参考。然后在只运行一次的useEffect 回调中,您可以将retrieveMargin 设置为窗口上resize 事件的回调。
    • 你有可以展示的例子吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-20
    • 1970-01-01
    • 2013-12-29
    • 2016-07-19
    相关资源
    最近更新 更多