js 让textarea的高度自适应父元素的高度

摘要:textarea按照普通元素设置height是没有作用的,可以这么来设置,下面给上一段项目代码。动态textArea祖先元素节点的高度,myCener是整个页面高度,otherDiv是textArea的祖先元素以外的其他高度

textarea按照普通元素设置height是没有作用的,可以这么来设置,下面给上一段项目代码


JS代码:

$.fn.extend({
    txtaAutoHeight: function () {
        return this.each(function () {
            var $this = $(this);
            if (!$this.attr('initAttrH')) {
                $this.attr('initAttrH', $this.outerHeight());
            }
            setAutoHeight(this).on('input', function () {
                setAutoHeight(this);
            });
        });
        function setAutoHeight(elem) {
            var $obj = $(elem);
            //让textArea自动调节高度,使其不出现滚动条
            //return $obj.css({ height: $obj.attr('initAttrH'), 'overflow-y': 'hidden' }).height(elem.scrollHeight);
            //让textArea自动适应父元素的高度
            var $parentDom = $obj.parent();
            return $obj.css({ height: $obj.attr('initAttrH'), 'overflow-y': 'hidden' }).height($parentDom.height());
        }
    }
});

/**
 * 动态textArea祖先元素节点的高度,myCener是整个页面高度,otherDiv是textArea的祖先元素以外的其他高度,
 * 利用(总高度-其他元素高度),来设置textArea祖先元素的高度
 * @returns
 */
function setAutoTextAreaHeightFun(){
	var totalHeight = $('#myCener').height();
	var height1 = 0;
	if(!$('#otherDiv').is(":hidden")){
		height1 = $('#otherDiv').height();
	}
	var textAreaHeight = totalHeight - height1;
	$('.textAreaParent').height(textAreaHeight-8);
}

本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!

链接: https://shenqiku.cn/article/FLY_5933