简体   繁体   中英

why is style.height not being added?

I have the below code and it runs without any issues but for some reason the height is never set.

function expandTextarea() {
    var textareas = document.getElementsByTagName('textarea');
    for (var i = 0; i < textareas.length; i++) {
        if (textareas[i].scrollHeight > 100) {
            textareas[i].style.height = textareas[i].scrollHeight + 'px !important';
        } else {
            textareas[i].style.height = '100px !important';
        }
    }
}

The old for this exact same function is,

jQuery('.disabled-textarea').each(function() {
    if(jQuery(this).prop('scrollHeight') > '100') {
        jQuery(this).attr('style', "height:" + jQuery(this).prop('scrollHeight') + "px !important");
    } else {
        jQuery(this).attr('style', "height: 100px !important");
    }
});

It works without any issues. I am just trying to move away from jQuery.

Removing !important fixes it:

 function expandTextarea() { var textareas = document.getElementsByTagName('textarea'); for (var i = 0; i < textareas.length; i++) { console.log(textareas[i].scrollHeight); if (textareas[i].scrollHeight > 100) { textareas[i].style.height = textareas[i].scrollHeight + 'px'; } else { textareas[i].style.height = '100px'; } } } expandTextarea(); 
 <textarea> </textarea> 

如果需要!important尝试:

textareas[i].style.cssText='height: 100px !important';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM