英文:
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:
<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 of main --}}
<aside class="flex absolute inset-y-0 left-0 bg-gray-400 z-20" :style="`width: ${width}px;`"></aside>
{{-- aside of blog --}}
<aside class="absolute -right-full w-52 bg-gray-400"></aside>
</header>
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论