2017-06-13 33 views
0

在网页上,我将设置几个textarea元素的高度以匹配其内容。我尝试了不同的方法,如在加载javascript时设置多个textarea元素的高度

var textarea = document.querySelectorAll('textarea'); 

$(document).ready(function(){ 
    for(var i = 0; i < textarea.length; i++){ 
    console.log("textarea="+textarea[i]); 
    $("textarea").height($("textarea")[i].scrollHeight); 
} 
}); 

但这种设置的第一个元素的高度,以最后一个元素的高度,可以看出here

如何确保页面上的每个textarea元素的高度设置为适合加载的内容?

回答

2

尝试使用.each() jQuery函数来遍历所有的文字区域与选择this结合,以选择合适的textarea

$(function(){ 
    $('textarea').each(function(){ 
     $(this).height($(this)[0].scrollHeight); 
    }); 
}); 
0

$("textarea").height将同时改变所有文字区域的高度在页面上。因此,为什么你会得到它将它们全部设置为最后一个高度的效果。

,如果你不混合jQuery和JS的语法很简单:

var textAreas = $("textarea"); //get textAreas as a jQuery object 

//loop through all the jQuery textarea objects 
textAreas.each(function(index, element) { 
    var textArea = $(this); //select only the current textArea in the loop 
    textArea.height(textArea.get(0).scrollHeight); //.get(0) gets the underlying HTML element which has the scrollHeight property 
}); 
0

$("textarea")找到您的网页上的所有文字区域。所以通过设置$("textarea").height它将设置所有的高度。因此只有最后的变化实际上保持不变。

相反,我们可以遍历数组,只调整当前的textarea。这可以用基本的javascript完成:

$(document).ready(function(){ 
    var textareas = document.querySelectorAll('textarea'); 
    for(var i = 0; i < textarea.length; i++){ 
     textarea[i].style.height = textarea[i].scrollHeight + "px"; 
    } 
}); 

看到它在这工作fiddle

我知道我的解决方案并不像使用jQuery的.each()那样干净,但它很容易理解,对于不使用jQuery的用户来说很好。 (但是请注意,$(document).ready(function() {应替换为document.addEventListener("DOMContentLoaded", function(e) {

相关问题