标签 textarea 下的文章

根据文本域(Textarea)内容自动调整高度

  • html部分
<textarea data-adaptheight rows="3" cols="40" placeholder="Your input"
style="padding: 16px; line-height: 1.5;"></textarea>
  • js部分
(function() {
    function adjustHeight(textareaElement, minHeight) {
        // compute the height difference which is caused by border and outline
        var outerHeight = parseInt(window.getComputedStyle(el).height, 10);
        var diff = outerHeight - el.clientHeight;

        // set the height to 0 in case of it has to be shrinked
        el.style.height = 0;

        // set the correct height
        // el.scrollHeight is the full height of the content, not just the visible part
        el.style.height = Math.max(minHeight, el.scrollHeight + diff) + 'px';
    }


    // we use the "data-adaptheight" attribute as a marker
    var textAreas = document.querySelectorAll('textarea[data-adaptheight]');

    // iterate through all the textareas on the page
    for (var i = 0, l = textAreas.length; i < l; i++) {
        var el = textAreas[i];

        // we need box-sizing: border-box, if the textarea has padding
        el.style.boxSizing = el.style.mozBoxSizing = 'border-box';

        // we don't need any scrollbars, do we? :)
        el.style.overflowY = 'hidden';

        // the minimum height initiated through the "rows" attribute
        var minHeight = el.scrollHeight;

        el.addEventListener('input', function() {
            adjustHeight(el, minHeight);
        });

        // we have to readjust when window size changes (e.g. orientation change)
        window.addEventListener('resize', function() {
            adjustHeight(el, minHeight);
        });

        // we adjust height to the initial content
        adjustHeight(el, minHeight);
    }
}());

示例:http://jsfiddle.net/5h4fauq8/1/
原文:http://web.jobbole.com/81906/

textarea的Tab缩进

我们常常习惯了在各种代码编辑器里使用tab进行代码缩进,增加代码可读性和美观,通常在Markdown中也有tab缩进区分等级,例如列表序列,二级列表在开头会多缩进一点。那么问题来了,一按tab焦点就自动转移了下一个html元素上了,不免大失所望。

现在推荐一款轻量的js插件解决这个问题,tabIndent.js

调用方法


  • 先引入js文件
<script src="tabIndent.js"></script>
  • 对页面所有textarea都可tab缩进
tabIndent.renderAll();
  • 也可针对某个textarea单独设置
var el = document.getELementById('#targetTextArea');
tabIndent.render(el);
  • 也可以动态删除他们的tab效果
// 全部清掉效果
tabIndent.removeAll();
// 清楚某个元素的tab效果
var el = document.getElementById('#textareaWithTabIndent');
tabIndent.remove(el);

Typecho系统的后台文章新增/编辑的textarea框增加tab效果


  • 先把tabIndent.js文件放入admin/js/目录下
  • admin/write-js.php文件的第五行添加如下代码
<script src="<?php $options->adminStaticUrl('js', 'tabIndent.js'); ?>"></script>
  • admin/write-js.php中的<script>标签的尾部也就是ready事件的底部,第258行添加如下代码
// textarea框的tab缩进
var textArea = document.getElementById('text');
tabIndent.render(textArea);