减少移动版本的文本区域行数

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

reduce number of rows textarea for mobile version

问题

我在表单中有一个文本区域

<textarea class="js-message" name="message" id="message" rows="6"></textarea>

我设置了 rows="6",但我需要在屏幕宽度小于767时将其设置为 rows="3"

我尝试过的选项只是根据屏幕高度更改此字段的高度,但这不是我所需要的。

英文:

I have a textarea in my form

<textarea class="js-message" name="message" id="message" rows="6"></textarea>

I set rows="6", but I need to make it so that for screens below 767 it was rows="3"

The option I tried to do is just change the height for this field depending on the screen, but this is not what I need

答案1

得分: 1

要修改文本区域的 rows 属性,必须使用JavaScript来完成,因为CSS的替代方法是通过调整高度来实现。

  • 使用 window.innerWidth 来获取窗口的宽度,以便在移动设备上进行测试。
  • 将函数附加到窗口的 resize 事件上,以触发更改 rows 属性的代码。
function changeRows() {
    const textarea = document.getElementById("message");
    if (window.innerWidth <= 767) {
        textarea.setAttribute("rows", "3");
    } else {
        textarea.setAttribute("rows", "6");
    }
}

window.addEventListener("resize", changeRows);
<textarea class="js-message" name="message" id="message" rows="6"></textarea>
英文:

To modify the textarea rows attribute, it would have to be done using Javscript since the CSS alternative is to adjust by height.

  • Use window.innerWidth to the get width of the window to test against for mobile.
  • Attach function to a window resize event to trigger code to change rows attribute

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

function changeRows() {
    const textarea = document.getElementById(&quot;message&quot;);
    if (window.innerWidth &lt;= 767) {
        textarea.setAttribute(&quot;rows&quot;, &quot;3&quot;);
    } else {
        textarea.setAttribute(&quot;rows&quot;, &quot;6&quot;);
    }
}

window.addEventListener(&quot;resize&quot;, changeRows);

<!-- language: lang-html -->

&lt;textarea class=&quot;js-message&quot; name=&quot;message&quot; id=&quot;message&quot; rows=&quot;6&quot;&gt;&lt;/textarea&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月19日 08:55:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76503075.html
匿名

发表评论

匿名网友

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

确定