改变元素宽度在 Windows 调整大小时使用 Alpine.js。

huangapple go评论52阅读模式
英文:

change width of an element on windows resize with alpine.js

问题

我使用**:resize.window指令来跟踪窗口大小变化,并通过样式属性更改元素的宽度**,但该指令只在Alpine初始化时有效一次。
请查看我的示例代码:

<header x-data="{width: 0}">
    <div class="flex justify-between items-center py-1">
        <x-blog.search/>
        <div class="flex">
            <div><x-blog.hamburger-right/></div>
            <div class="border-l sm:border-l-2 border-gray-100 dark:border-gray-800 my-2" :resize.window="width = $el.offsetLeft"></div>
            <div><x-blog.hamburger-left/></div>
        </div>
        <x-dark-mode-switch/>
    </div>

    {{-- 除主内容外的部分 --}}
    <aside class="flex absolute inset-y-0 left-0 bg-gray-400 z-20" :style="`width: ${width}px;`"></aside>
    {{-- 博客侧边栏 --}}
    <aside class="absolute -right-full w-52 bg-gray-400"></aside>
</header>

我不明白为什么这不起作用,但如果有任何错误的话,如果您告诉我,我将不胜感激。

英文:

I used :resize.window directive to track windows resize and change an element width with style properties but that directive works only one time when alpine initiates.
please look at my sample code:

&lt;header x-data=&quot;{width: 0}&quot;&gt;
    &lt;div class=&quot;flex justify-between items-center py-1&quot;&gt;
        &lt;x-blog.search/&gt;
        &lt;div class=&quot;flex&quot;&gt;
            &lt;div&gt;&lt;x-blog.hamburger-right/&gt;&lt;/div&gt;
            &lt;div class=&quot;border-l sm:border-l-2 border-gray-100 dark:border-gray-800 my-2&quot; :resize.window=&quot;width = $el.offsetLeft&quot;&gt;&lt;/div&gt;
            &lt;div&gt;&lt;x-blog.hamburger-left/&gt;&lt;/div&gt;
        &lt;/div&gt;
        &lt;x-dark-mode-switch/&gt;
    &lt;/div&gt;


    {{-- aside of main --}}
    &lt;aside class=&quot;flex absolute inset-y-0 left-0 bg-gray-400 z-20&quot; :style=&quot;`width: ${width}px;`&quot;&gt;&lt;/aside&gt;
    {{-- aside of blog --}}
    &lt;aside class=&quot;absolute -right-full w-52 bg-gray-400&quot;&gt;&lt;/aside&gt;
&lt;/header&gt;

I don't understand why that doesn't work but if there is any mistake I will be grateful if you let me know

答案1

得分: 1

你可以尝试这个链接 https://codesandbox.io/s/laughing-cherry-7bn7pr?file=/index.html

根据文档中所述,

> 当存在 .window 修饰符时,Alpine 将在页面的根窗口对象上注册事件监听器,而不是在元素本身上。

这意味着 $el 将变成 window 对象,因此您需要使用 x-ref 来获取元素。

英文:

you try this https://codesandbox.io/s/laughing-cherry-7bn7pr?file=/index.html

As stated in documentation,

> When the .window modifier is present, Alpine will register the event listener on the root window object on the page instead of the element itself.

It means the $el will becoming to the window object, thus you need to use x-ref to get the element.

huangapple
  • 本文由 发表于 2023年3月15日 20:32:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75744742.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定