Phoenix LiveView中静态与动态textarea独立样式设置问题
问题:Phoenix中静态与动态textarea样式冲突的解决方法
在Phoenix的html.heex文件中同时使用静态<textarea>标签和Phoenix动态组件<.input type='textarea' />时,样式设置遇到了麻烦:用form textarea选择器给动态textarea加样式,会连带影响带.line-numbers类的静态textarea,导致静态textarea的样式被覆盖,只能靠一堆!important强制生效,这明显不是规范写法,得找正确的样式设置方式。
当前代码
html.heex文件
<div class="flex"> <textarea id="line-numbers" class="line-numbers rounded-bl-md" readonly> <%= "1 " %> </textarea> <.input field={@form[:markup_text]} type="textarea" class="markup-input" placeholder="Insert code..." spellcheck="false" autocomplete="off" phx-debounce="blur" /> </div>
CSS文件
form textarea { @apply bg-emDark-dark font-brand font-regular text-xs border border-white h-[300px] resize-none; border-top-left-radius: 0 !important; /*!important seems to be a cheat code when css is misbehaving. doesn't work otherwise*/ border-top-right-radius: 0 !important; color: white !important; margin-top: 0 !important; width: 300px !important; /*This affects both textareas but I want it to only affect the dynamic textarea*/ } form textarea { @apply focus:outline-none focus:border-white } .line-numbers { @apply border border-white font-brand font-regular text-xs text-emDark-light bg-emDark-dark h-[300px] w-[54px] text-right overflow-hidden resize-none; border-right: none; border-top: none; } .line-numbers:focus { @apply focus:outline-none focus:border-white focus:ring-0; }
解决方案
1. 精准定位动态textarea
Phoenix的.input组件会把你设置的class加到外层容器上,内部的textarea是它的子元素。直接用这个自定义class来写选择器,就能只针对动态textarea生效,不会影响静态的:
/* 只给动态textarea加样式 */ form .markup-input textarea { @apply bg-emDark-dark font-brand font-regular text-xs border border-white h-[300px] resize-none; border-top-left-radius: 0; border-top-right-radius: 0; color: white; margin-top: 0; width: 300px; } form .markup-input textarea:focus { @apply focus:outline-none focus:border-white }
另外,也可以利用组件自动生成的phx-feedback-for属性来定位,这个属性值对应你的表单字段名markup_text:
form [phx-feedback-for="markup_text"] textarea { /* 同上样式 */ }
2. 提高静态textarea选择器优先级
如果不想改动态textarea的选择器,给静态textarea的选择器加个form前缀,提升优先级,这样就不用!important了:
form .line-numbers { @apply border border-white font-brand font-regular text-xs text-emDark-light bg-emDark-dark h-[300px] w-[54px] text-right overflow-hidden resize-none; border-right: none; border-top: none; } form .line-numbers:focus { @apply focus:outline-none focus:border-white focus:ring-0; }
3. 移出静态textarea到form外(可选)
如果静态的行号textarea不需要在form标签里,直接把它移到form外面,form textarea选择器就碰不到它了,这是最直接的办法。
内容的提问来源于stack exchange,提问作者Duck Dodgers
相关产品推荐
相关产品推荐

