Last active
October 29, 2017 05:11
-
-
Save yiyizym/6e9eb583dafe1d0a335235a3de18157f to your computer and use it in GitHub Desktop.
textarea_auto_height
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta http-equiv="content-type" content="text/html;charset=utf-8"> | |
<style> | |
textarea{ | |
padding: 5px; | |
font-size: 14px; | |
height: 14px; | |
line-height: 1; | |
} | |
textarea.multilines{ | |
line-height: 1.2; | |
} | |
</style> | |
</head> | |
<body> | |
<div id="container"> | |
<textarea></textarea> | |
</div> | |
<script type="text/javascript"> | |
document.addEventListener('DOMContentLoaded', function(){ | |
var textarea = document.querySelector('textarea'); | |
var maxLineCount = 5; | |
function getStyleValue(el, name){ | |
return Number(window.getComputedStyle(el)[name].replace('px','')); | |
} | |
function getVerticalPadding(){ | |
return getStyleValue(textarea,'paddingTop') + getStyleValue(textarea,'paddingBottom') | |
} | |
function getScrollHeight(){ | |
return textarea.scrollHeight; | |
} | |
function getLineHeight(){ | |
return getStyleValue(textarea, 'lineHeight'); | |
} | |
function isMultilines(){ | |
return getScrollHeight() > getVerticalPadding() + getLineHeight(); | |
} | |
function shouldShowScrollBar(){ | |
return getScrollHeight() > maxLineCount * getLineHeight(); | |
} | |
textarea.addEventListener('input', function(){ | |
this.style.height = '0'; | |
this.classList.toggle('multilines', isMultilines()); | |
if(shouldShowScrollBar()){ | |
this.style.height = maxLineCount * getLineHeight() + 'px'; | |
this.style.overflowY = 'scorll'; | |
} else { | |
this.style.height = getScrollHeight() - getVerticalPadding() + 'px'; | |
} | |
}) | |
}) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment