zhangxinxu / quiz

小测答题收集区
536 stars 43 forks source link

DOM基础测试36 #40

Open zhangxinxu opened 5 years ago

zhangxinxu commented 5 years ago

本期题目如下,文本域相关:

已知有CSS:

textarea { line-height: 20px; }

大家提交回答的时候,注意缩进距离,起始位置从左边缘开始;另外,github自带代码高亮,所以请使用下面示意的格式(缩进和代码高亮1积分)。

```js
// 你的JS代码写在这里
 ```

**心怀瑞雪,自己作答,不要参考别人回答**

其他 因白天有应酬,本期小测答疑直播为8月24日晚上19:00,预计半小时左右。直播地址:https://live.bilibili.com/21193211

每位答题者会有至少2积分参与分,本次小测满分10积分。

首位答题者会100%被翻牌。

wingmeng commented 5 years ago

第 1 题:

// 方法1
const myTextarea = document.querySelector('textarea');

// 方法2
const myTextarea = document.getElementsByTagName('textarea')[0];

第 2 题:

// 方法1
myTextarea.rows = 5;

// 方法2
myTextarea.setAttribute('rows', 5);

第 3 题:

// 用 clientHeight  获取会包含 padding,所以用下面方法获取计算样式来得到高度
const { height } = window.getComputedStyle(myTextarea);
console.log(height);  // Chrome: 75px, FF: 112px

第 4 题:

textarea 默认的 lineHeight 值为 normal,此时是无法计算的,而且每个浏览器解析出的 normal 数值存在差异,另外它的值还和字体有关。详情 所以想要实现题目中的要求的话,有个大前提就是必须通过 CSS Reset 的方式对 textarea 的行高进行预定义,我这里采用了 Normalize.css 中的相关样式:

textarea {line-height: 1.15;}

然后就可以正常获取行高进行后续计算了:

const { lineHeight } = window.getComputedStyle(myTextarea);
myTextarea.style.height = parseFloat(lineHeight) * myTextarea.rows + 'px';

第 5 题:

起先想到了用 MutationObserver,发现 IE11+ 才支持,所以采用监听 DOM 节点的 API 来实现。 网上说 DOMNodeInserted 事件在 IE9 下有bug:(传送门

Note that the DOMNodeInserted event is buggy in Internet Explorer 9, it is not fired when a node is inserted for the first time. See the examples below for details.

实际在 IE11 通过文档模式模拟 IE9 时没有发现这个bug,由于手头没有原生 IE9,所以不好做判断

document.addEventListener('DOMNodeInserted', function(event) {
  var elm = event.target;

  if (elm.nodeName.toLowerCase() === 'textarea') {
    var lineHt = window.getComputedStyle(elm).lineHeight;
    elm.style.height = parseFloat(lineHt) * elm.rows + 'px';
  }
});
fzpijl commented 5 years ago

1.

var textarea = document.querySelector('textarea')

2.

textarea.rows = 5

3.

//用视口高度减去上下padding
var contentHeight = textarea.clientHeight - parseFloat(getComputedStyle(textarea).paddingTop) - parseFloat(getComputedStyle(textarea).paddingBottom)

4.

//先设置一个lineHeight再获取值
textarea.style.lineHeight = 1.5
var lineHeight = parseFloat(getComputedStyle(textarea).lineHeight)
textarea.style.height = 5 * lineHeight

5.

JaimeCheng commented 5 years ago
// 1
const text = document.getElementsByTagName('textarea')[0]

// 2
text.rows = 5

// 3
const height = window.getComputedStyle(text).height

// 4 
// 默认获取到的lineHeight是normal只好先设置一下值了
text.style.lineHeight = 1.5
const lineHeight = parseFloat(window.getComputedStyle(text).lineHeight)
text.style.height = text.rows * lineHeight + 'px'

// 5 
// 只想到监听DOMNodeInserted事件,但是应该不对
// 跟题目里说的一样,还是每次添加textarea重新执行一遍样式设置
document.body.addEventListener('DOMNodeInserted', (e) => {
  const dom = e.target
  if (dom.nodeName.toLowerCase() === 'textarea') {
    var originalLH = parseFloat(window.getComputedStyle(dom).lineHeight)
    if (isNaN(originalLH)) {
      dom.style.lineHeight = 1.5
      originalLH = parseFloat(window.getComputedStyle(dom).lineHeight)
    }
    dom.style.height = dom.rows * originalLH + 'px'
  }
})
guqianfeng commented 5 years ago
    let oTextArea = document.querySelector("textarea");
    oTextArea.setAttribute("row", 5);
    let {lineHeight, paddingTop, paddingBottom} = window.getComputedStyle(oTextArea);
    console.log(lineHeight); //normal,什么鬼,那换个方式计算,我想了下content高度应该就是用clientHeight减去paddingTop和paddingBottom
    console.log(paddingTop); // 2px
    console.log(paddingBottom); // 2px
    let cH = oTextArea.clientHeight; //154
    let contentHeight = cH - parseFloat(paddingTop) - parseFloat(paddingBottom);
    let rowValue = oTextArea.getAttribute("row"); //前面设置的5
    oTextArea.style.height = contentHeight * rowValue + "px";

    //以下代码测试了下dom节点插入监听,记得有这么个属性,测试没问题
    // document.body.addEventListener("DOMNodeInserted", () => {
    //     alert(1);
    // })
    // document.body.appendChild(document.createElement("div"));
    // document.body.appendChild(document.createElement("p"));

    document.body.addEventListener("DOMNodeInserted", (e) => {
        let node = e.target;
        if(node.nodeName.toLowerCase() === "textarea"){
            let {paddingTop, paddingBottom} = window.getComputedStyle(node);
            let contentHeight = node.clientHeight - parseFloat(paddingTop) - parseFloat(paddingBottom);
            let rowValue = node.getAttribute("row");
            node.style.height = contentHeight * rowValue + "px";
        }
    });
    //以下代码测试用
    for (let i = 0; i < 10; i++) {
        let insertNode = document.createElement("textarea");
        insertNode.setAttribute("row", ~~(Math.random() * 10 + 1));
        document.body.appendChild(insertNode);
    }
GitHdu commented 5 years ago
//1
const oTxtarea = document.querySelector('textarea');
//2
oTxtarea.rows=5
//3
const { height } = oTxtarea.getBoundingClientRect()
//4
const {lineHeight} = getComputedStyle(oTxtarea)
oTxtarea = parseFloat(lineHeight)*oTxtarea.rows+'px'
rayj1993 commented 5 years ago
textarea {
    line-height: 20px;
}

1

let textarea = document.querySelector('textarea');

2

textarea.setAttribute('rows', 5);
textarea.rows = 5;

3

let height = document.defaultView.getComputedStyle(textarea, null)['height'];

4

let lineHeight = parseFloat(document.defaultView.getComputedStyle(textarea, null)['line-height'])
textarea.style.height = textarea.rows * lineHeight + 'px'

5

// 在一个节点作为子节点被插入到另一个节点中时触发; 
document.addEventListener('DOMNodeInserted', function (event) {
let textarea = event.target;
let lineHeight =  parseFloat(document.defaultView.getComputedStyle(textarea, null)['line-height']);
textarea.style.height = lineHeight * textarea.rows + 'px';
});
PLQin commented 5 years ago

1.

let ta = document.getElementsByTagName('textarea')[0]; 
console.log(ta.clientHeight) // 获得textarea元素

2.

let ta = document.getElementsByTagName('textarea')[0];
ta.setAttribute('row', 5) // 设置textarea的属性

3.

let ta = document.getElementsByTagName('textarea')[0];
let ta_height = ta.clientHeight;
console.log(ta.clientHeight) // 获得textarea的高度(不包括border和padding)

4.

let ta = document.getElementsByTagName('textarea')[0];
let ta_lineheight = ta.style.lineHeight ;
let ta_row = document.getElementsByTagName('textarea')[0].getAttribute('row') ;
ta.style.height = ta_lineheight * ta_row + 'px' ;  // 设置textarea的高度为行高与row的积

5.

/**
 * 插入html, 文本域高度自动变为row的属性值和行高的乘积
 * @param {*DocumentObject} texta 文本域
 * @param {*String} str 字符串
 * @return {*DocumentObject} 此textarea
 */
function setTextareaHeight(texta, str) {
  let ta = texta;

  ta_text = ta.innerHTML + str;
  ta.innerHTML = ta_text;

  let ta_lineheight = ta.style.lineHeight ;
  let ta_row = texta.getAttribute('row') ;

  ta.style.height = ta_lineheight * ta_row + 'px' ;  // 设置textarea的高度为行高与row的积

  return ta;
}
ZhangXDong commented 5 years ago

html:

<textarea>测试</textarea>

css:

textarea {
    line-height: 30px;
}

1.

let textareaEl = document.getElementsByTagName('textarea')[0]

2.

textareaEl.setAttribute('row', 5)

3.

let lineHeight = Number.parseFloat(window.getComputedStyle(textareaEl)['line-height'])

4.

textareaEl.style.height = lineHeight * textareaEl.getAttribute('row') + 'px'

5.

Despair-lj commented 5 years ago
// 1
var textarea = document.querySelector('textarea');
// 2
textarea.setAttribute('rows', '5');
// 3
var textareaHeight = window.getComputedStyle(textarea).height;
// 4
textarea.style.height =
  calcLineHeight(textarea) * textarea.getAttribute('rows') + 'px';

/**
 * 返回 HTML 元素的 line-height
 * 在 Chrome 没有赋值行高 getComputedStyle 方法返回值 normal, 通过计算获取
 * 在 FireFox 和 Safari 中 getComputedStyle 直接返回计算结果
 * 
 * @param {Node} element 一个HTML元素
 * @returns {String} 返回一个高度数字
 */
function calcLineHeight(element) {
  var style = window.getComputedStyle(element, null);
  var lineHeight = parseFloat(style.getPropertyValue('line-height'), 10);

  if (isNaN(lineHeight)) {
    var span = document.createElement('span');
    span.style.display = 'inline-block';
    span.style.fontFamily = style.fontFamily;
    span.style.fontSize = style.fontSize;
    span.style.opacity = 0;
    span.innerHTML = 'lj';
    document.body.appendChild(span);

    var spanStyle = window.getComputedStyle(span);
    lineHeight = parseFloat(spanStyle.height);
    document.body.removeChild(span);
  }
  return lineHeight;
}

5


textarea {
  margin: 0;
  padding: 0;
  font-size: 16px;
  line-height: 1.15;
  /* 隐藏 FireFox 浏览器 textarea 默认 x 轴高度 */
  overflow-x: hidden;
  font-family: inherit;
}
`
livetune commented 5 years ago

第一题

var textArea = document.querySelector('textarea')

第二题

textArea.rows = 5

第三题

var textAreaStyle = window.getComputedStyle(textArea)
console.log(textAreaStyle.height)

第四题

var normalLineHeight = (function () {
    var elm = document.createElement('textarea')
    elm.rows = 1
    elm.style.lineHeight = "normal"
    elm.style.border = "none"
    elm.style.padding = "0"
    elm.style.position = "fixed"
    document.body.append(elm)
    var height = elm.clientHeight
    elm.remove()
    return height
})()

var textAreaLineHeight = textAreaStyle.lineHeight.replace(/(\d+)(?:px)/, '$1')

if (textAreaLineHeight === 'normal') {
    textAreaLineHeight = normalLineHeight
}

textArea.style.height = textAreaLineHeight * textArea.rows + 'px'

第五题

document.addEventListener("DOMNodeInserted", function (event) {
    if (event.srcElement.tagName === 'TEXTAREA') {
        var textAreaLineHeight = textAreaStyle.lineHeight.replace(/(\d+)(?:px)/, '$1')

        if (textAreaLineHeight === 'normal') {
            textAreaLineHeight = normalLineHeight
        }
        console.log(textAreaLineHeight)
        event.target.style.height = textAreaLineHeight * event.target.rows + 'px'
    }
}
zy017 commented 5 years ago
// 1
var textarea = document.querySelector('textarea')
// 2
textarea.rows = 5
// 3
var height = window.getComputedStyle(textarea,null).getPropertyValue("height")
// 4
var lineHeight = window.getComputedStyle(textarea,null).getPropertyValue("line-height")
var fontSize = window.getComputedStyle(textarea,null).getPropertyValue("font-size")
// 由于 lineHeight 是 normal 取约等值 1.2
if (lineHeight === 'normal') {
    lineHeight = Math.round(parseFloat(fontSize) * 1.2)
} else {
    lineHeight = Math.round(parseFloat(lineHeight))
}
textarea.style.height = lineHeight * textarea.rows + 'px'
// 5
document.addEventListener('DOMNodeInserted', function (event) {
    var textarea = event.target
    if (textarea.tagName === 'TEXTAREA') {
        var lineHeight = window.getComputedStyle(textarea,null).getPropertyValue("line-height")
        var fontSize = window.getComputedStyle(textarea,null).getPropertyValue("font-size")
        // 由于 lineHeight 是 normal 取约等值 1.2
        if (lineHeight === 'normal') {
            lineHeight = Math.round(parseFloat(fontSize) * 1.2)
        } else {
            lineHeight = Math.round(parseFloat(lineHeight))
        }
        textarea.style.height = lineHeight * textarea.rows + 'px'
    }
})
liyongleihf2006 commented 5 years ago

第一题

var textarea = document.querySelector('textarea');
console.dir(textarea);

第二题

//textarea.rows = 5;
/* 使用这种写法是我做的第五题后改的 */
textarea.setAttribute("rows",5);

第三题

var computedStyle = window.getComputedStyle(textarea);
var height = computedStyle.height;
console.log(height);

第四题

var fontSize = parseFloat(computedStyle.fontSize);
//lineHeight是 normal 的时候,我查资料大约是fontSize的1.2倍
//Depende del agente del usuario. Los navegadores de escritorio (incluido Firefox) usan un valor por defecto de apenas 1.2, dependiendo del font-family del elemento.
var lineHeight = parseFloat(computedStyle.lineHeight)||fontSize*1.2;
textarea.style.height = lineHeight*textarea.rows + "px";

第五题

/* 我是使用css的方式做的,这里的实现是需要规定textarea的line-height是一个固定的值,然后使用css将rows=1,2,3,4....,100,....200的高度预设好 */
textarea{
  line-height: 16px;
}
textarea[rows="1"]{
  height:calc( 16px * 1 )
}
textarea[rows="2"]{
  height:calc( 16px * 2 )
}
/* …… */
textarea[rows="5"]{
  height:calc( 16px * 5 )
}
/* …… */
textarea[rows="8"]{
  height:calc( 16px * 8 )
}
/* …… */
textarea[rows="100"]{
  height: calc( 16px * 100 );
}
/* …… */
textarea[rows="200"]{
  height: calc( 16px * 200 );
}
CandyQiu commented 5 years ago

写了一半~先占个坑 https://codepen.io/CandyQiu/pen/NWKbaaq

// 1.
let  textarea = document.getElementsByTagName("textarea");

// 2
textarea[0].rows = 5;

// 3

// 4

// 5
zengqingxiao commented 5 years ago

第一问

 let textareaEle = document.querySelectorAll('textarea');
 console.log(textareaEle[0]);

第二问

    textareaEle[0].setAttribute('rows', 5);
    console.log(textareaEle[0]);

第三问

    /**
     *
      获取元素的浏览器中最终渲染效果的样式
     *
     @method setstyle
     *
     @param {object} [element] 元素名
     *
     @param {string} [type] 需要查找的样式名称,小驼峰格式
     *
     @return {srting || Number} 获取到的样式的值
    */
    function setstyle(element, type) {
      if (element.currentStyle) {
        return element.currentStyle.type
      } else {
        return getComputedStyle(element, null)[type]
      }
    }
    let textareaEleHeight = setstyle(textareaEle[0], 'height');
    console.log(textareaEleHeight)

第四问

    let textareaEleLineHeight = setstyle(textareaEle[0], 'lineHeight');
    console.log(textareaEleLineHeight);
    let textareaElefontSize = setstyle(textareaEle[0], 'fontSize');
    console.log(textareaElefontSize)
    // console.log(textareaEle[0].getAttribute('rows'))
    if (textareaEleLineHeight === 'normal') {
      // 默认值约为1.2
      let height = textareaEle[0].getAttribute('rows') * 1.2 * parseInt(textareaElefontSize)
      textareaEle[0].style.height = height;
    } else if (textareaEleLineHeight.slice(-2) === 'px') {
      let height = textareaEle[0].getAttribute('rows') * parseInt(textareaEleLineHeight)
      textareaEle[0].style.height = height;
    }

第五问

theDrunkFish commented 5 years ago

题目1

var txt = document.querySelector('textarea');

题目2

txt.rows = 5;

题目3

var txtH = getComputedStyle(txt).height;

题目4

var globalLineHeight = 1.5;
function setTextareaHeight(el, lineH){
    var elStyle = getComputedStyle(el);

    if(elStyle.lineHeight === 'normal'){
        el.style.lineHeight = lineH || globalLineHeihgt;
    }
    el.style.height = parseFloat(elStyle.lineHeight) * el.rows + 'px';
}

题目5

document.addEventListener('DOMNodeInserted', function(e){
    var target = e.target;
    var targetIter = document.createNodeIterator(target, NodeFilter.SHOW_ELEMENT);
    var node = null;

    while(node = targetIter.nextNode()){
        if(node.nodeName.toLowerCase() === 'textarea'){
            setTextareaHeight(node);
        } 
    }
}, false)
Seasonley commented 5 years ago
var ele = document.querySelector("textarea");
setTextareaHeight(ele,5);
function setTextareaHeight(ele,rows){
    var  _ = window.getComputedStyle(ele),
        ele_pt = parseFloat(_.paddingTop),
        ele_pb = parseFloat(_.paddingBottom),
        ele_row= ele.rows;
    ele.rows = rows;
    var ele_height = ele.clientHeight - ele_pt - ele_pb;
    ele.style.height = ele_height / rows * ele_row + "px";
}
document.addEventListener('DOMNodeInserted', function(event) {
    var ele = event.target;
    ele.tagName==='TEXTAREA' && setTextareaHeight(ele,1)
});
XboxYan commented 5 years ago
//1.
var textarea = document.querySelector('textarea');
//2.
textarea .rows = 5;
//3.
getComputedStyle( textarea ).height;
//4.
function setHeight( textarea ){
    var styles = getComputedStyle(textarea);
    var lineHeight =  getComputedStyle(textarea).lineHeight;
    if ( lineHeight == 'normal' ){
        lineHeight = styles.fontSize.slice(0,-2)*1.2;//设置行高为1.2
    }else{
        lineHeight = lineHeight.slice(0,-2);
    }
    textarea.style.height = lineHeight * textarea.rows + 'px';
}
setHeight( textarea );
//5
document.addEventListener('DOMNodeInserted', function(ev) {
   var target = event.target;
   if ( target .tagName == 'TEXTAREA' ) {
      setHeight(target);
   }
});

另外,DOMNodeInserted是一个不太标准的事件,已从Web标准中删除,将来可用MutationObserver代替。 其次,实现监听元素插入还可以采用css动画,如下

给元素添加一点动画,记住这个动画名字show

textarea{
    opacity: 0;
    animation: show .3s linear forwards;
}
@keyframes show{
    from{
        opacity: 0;
    }
    to{
        opacity: 1;
    }
}

然后,添加animationstart回调,判断动画名称即可

document.addEventListener('animationstart',function(ev){
    if(ev.animationName == 'show'){
        //新元素出现了...
        console.log(ev.target);
    }
})

兼容性是IE10+

ziven27 commented 5 years ago

前四题

// 第一题
const textarea = document.getElementsByTagName('textarea')[0];

// 第二题
textarea.rows = 5;

// 第三题
const textTemp = textarea.cloneNode(true);
textTemp.style.borderWidth = 0;
textTemp.style.padding = 0;
textTemp.style.visible= 'hidden';
textTemp.style.position= 'absolute';
textTemp.id = 'temp';
document.body.appendChild(textTemp);

// 记录5行时候元素高度
const row5Height=textTemp.clientHeight;
console.log('textarea height=', row5Height);

// 第四题
textTemp.style.height = null;
textTemp.rows = 4;

// 记录4行元素高度
const row4Height = textTemp.clientHeight;
const lineHeight = row5Height - row4Height;
textarea.style.height = lineHeight * 5 + 'px';

// 移除参考元素
document.body.removeChild(textTemp);

第五题

textarea{
  box-sizing: border-box;
}
les-lee commented 5 years ago
    // 1
    var textarea = document.getElementsByTagName('textarea')[0]
    console.log(textarea)

    // 2
    textarea.rows = 8

    // 3
    console.log(window.getComputedStyle(textarea)['height'].slice(0, -2), 'height')

    //4  firefox 默认的行高是15.2 chrome 和ie 都是 默认都是 normal值...
    // 以上数据(本人机器实测的. 其他特殊情况或版本未知)
    var textarea_line_height = window.getComputedStyle(textarea)['line-height']
    textarea_line_height = textarea_line_height === 'normal' ? 15.2 : textarea_line_height.slice(0, -2)
    textarea.style.height = (textarea_line_height * textarea.rows) + 'px'
    console.log(textarea_line_height * textarea.rows)

    //5 DOMSubtreeModified, 实际项目还应加上防抖|节流
    // 注意这里不能用箭头函数了... 不兼容ie9 的可以用 MutationObserver() API 
    window.addEventListener('DOMSubtreeModified', function (e) {
      var textareas = document.getElementsByTagName('textarea')
      var textareasLenght = textareas.length
      for (var i = 0; i < textareasLenght; i++) {
        var textarea_line_height = window.getComputedStyle(textareas[i])['line-height']
        textarea_line_height = textarea_line_height === 'normal' ? 15.2 : textarea_line_height.slice(0, -2)
        textareas[i].style.height = (textarea_line_height * textarea[i].rows) + 'px'
        console.log(textarea_line_height * textarea.rows)
      }
    })
NeilChen4698 commented 5 years ago

1.

document.querySelector('textarea')

2.

document.querySelector('textarea').rows = 5

3.

window.getComputedStyle(document.querySelector('textarea'),null).getPropertyValue('height')

4.

var getLineHeight = function(ele) {
    return window.getComputedStyle(ele,null).getPropertyValue('line-height');
};
var autoAdjustTextarea = function(ele) {
    var lineHeight = getLineHeight(ele);
    if (lineHeight === 'normal') {
        ele.style.lineHeight = '1.2';
        lineHeight = getLineHeight(ele);
    }
    ele.style.height = parseFloat(lineHeight.substring(0, lineHeight.length - 2)) * ele.rows + 'px';
};
autoAdjustTextarea(document.querySelector('textarea'));

5.

var setAutoAdjustListener = function(ele) {
    autoAdjustTextarea(ele);
    ele.addEventListener('DOMAttrModified', function(e) {
        autoAdjustTextarea(ele);
    });
};
document.addEventListener("DOMNodeInserted", function(e) {
    if (e.srcElement.nodeName === 'TEXTAREA') {
        setAutoAdjustListener(e.srcElement);
    }
});
ghost commented 5 years ago

1

const t = document.querySelector('textarea')

2

t.rows = 5

3

const style = window.getComputedStyle(t, null)
const h = style.height

4

const {lineHeight, fontSize} = style
const fs = parseFloat(fontSize)
const rows = Number(t.rows)
t.style.height = fs * 1.2 * rows + 'px'

5

// 暂无思路
bugaosunihhh commented 5 years ago
<textarea></textarea>
<script type="text/javascript">
    // 第一题
    let textarea = document.querySelector("textarea");

    // 第二题
    textarea.rows = 5
    // textarea.setAttribute("rows",5)

    // 第三题
    let clientHeight = textarea.clientHeight; // 会四舍五入取整
    let clientRect = textarea.getBoundingClientRect();
    let { height, paddingTop, paddingBottom } = getComputedStyle(textarea)
    let trueHeight = clientRect.height - (parseFloat(paddingTop) + parseFloat(paddingBottom));
    console.log(trueHeight);

    // 第四题
    function setTextareaHeight(el,rows=el.rows) {
        // line-height 可以设置为 数值 百分比单位 px单位等,默认是normal
        let lineHeight = ''+getComputedStyle(textarea)["lineHeight"];
        let fontSize =  parseFloat(getComputedStyle(textarea)["fontSize"]);
        let height;

        if(lineHeight == 'normal'){
            el.style["lineHeight"] = 1.5;
            height = 1.5 * fontSize * rows;
        }else if(lineHeight.indexOf('%')){
            height = parseFloat(lineHeight)/100 * fontSize * rows;;
        }else if(lineHeight.indexOf('px')){
            height = parseFloat(lineHeight) * rows;
        }else{
            height = parseFloat(lineHeight) * fontSize * rows;
        }
        el.style["height"] = height + 'px';
    }
    setTextareaHeight(textarea);

    // 第五题
    document.body.addEventListener('DOMNodeInserted', function(e) {
        let target = e.target;
        if(target.nodeName.toLowerCase() == 'textarea'){
            setTextareaHeight(target);
        }
    });
</script>
lifelikejuly commented 5 years ago
silverWolf818 commented 5 years ago
//第一题
var dom = document.querySelector('textarea');
//第二题
dom.setAttribute('rows',5);
//第三题
var computedStyle = window.getComputedStyle(dom,null);
var height = computedStyle.height;
//第四题
dom.style.lineHeight = 1;
dom.style.height = parseFloat(computedStyle.lineHeight) * dom.getAttribute('rows') + 'px';
//第五题不会
asyncguo commented 5 years ago
1. let textareaEl = document.querySelector('textarea')
2. textareaEl.setAttribute('rows', 5)
3. window.getComputedStyle(textareaEl).height
4. 
  function setHeight(el) {
    let _lineHeight = window.getComputedStyle(el).lineHeight
    let _rows = el.getAttribute('rows')

    if (_lineHeight === 'normal') {
      let _fontSize = parseFloat(window.getComputedStyle(el).fontSize)
      el.style.height = `${1.2 * _fontSize * _rows}px`
    } else {
       el.style.height = `${parseFloat(_lineHeight) * _rows}px`
    }
  }
  setHeight(textareaEl)

5.
  document.addEventListener("DOMNodeInserted", function (ev) {
    if (ev.target.tagName === 'TEXTAREA') {
      setHeight(ev.target)
    }
  }, false)
kuikuiGe commented 5 years ago

1.

document.querySelector("textarea")

2.

document.querySelector("textarea").setAttribute("rows",5)

3.

window.getComputedStyle(document.querySelector("textarea")).height
frankyeyq commented 5 years ago

1.document.querySelector('textarea');
2. textarea.rows = 5;
3. getComputedStyle(textarea).height;
4. 
function setTextareaHeight(textarea) {
    let lineHeight = getComputedStyle(textarea)['line-height'];
    if (typeof lineHeight === 'normal') {
        lineHeight = parseInt(getComputedStyle(textarea)['font-size']) * 1.2;
    } else {
        lineHeight = parseInt(lineHeight);
    }
    textarea.style.height = lineHeight * textarea.rows + 'px';
}
setTextareaHeight(textarea);
5.
document.addEventListener("DOMNodeInserted", function (event) {
    if (event.target.tagName === 'TEXTAREA') {
      setTextareaHeight(event.target)
    }
  })
不知道怎么兼容ie9,想用calc来做,尝试了一下不行
sghweb commented 5 years ago
// 第一题
let area = document.querySelector("textarea")
// 第二题
area.setAttribute("rows", 5)
// 第三题
let height = getComputedStyle(area).height
// 第四题
// line-height 默认值为normal,不同桌面浏览器normal计算值不一样,与font-family有密切关系,所以重置一什值设为1.5
area.style.lineHeight = 1.5
const lineHeight = getComputedStyle(area).lineHeight
area.style.height = parseFloat(lineHeight) * area.rows + 'px'
// 第五题 没想到什么好的方法,用这个笨办法循环
let areas = document.querySelectorAll("textarea")
for (var i = 0; i < areas.length; i++) {
  areas[i].setAttribute("rows", 5)
  areas[i].style.lineHeight = 1.5
  const lineHeight = getComputedStyle(areas[i]).lineHeight
  areas[i].style.height = parseFloat(lineHeight) * areas[i].rows + 'px'
}
GCGligoudan commented 5 years ago
// 1.
const textarea = document.querySelector('textarea');
// 2.
textarea.setAttribute('row', 5);
// 3. 
const style = window.getComputedStyle(textarea, null);
const textareaHeight = style.getPropertyValue("height");
// 4.
const textareaLG = style.getPropertyPriority('line-height');
textarea.style.height = textareaLG * (textarea.getAttribute('row'));
// 5.
whrice commented 5 years ago

1.

var textarea=document.querySelector('textarea')

2.

textarea.setAttribute('rows',5)  

3.

console.log(window.getComputedStyle(textarea).height)

4.

  function setHeight(textarea){
        var lineHeight=window.getComputedStyle(textarea).lineHeight
        var fontSize=window.getComputedStyle(textarea).fontSize.slice(0,-2)
        console.log(fontSize)
        console.log(lineHeight)
       if(lineHeight=='normal'){
         lineHeight=fontSize*1.2;//设置默认行高属性1.2
       }
       else{
           lineHeight=lineHeight.slice(0,-2)
       }
       textarea.style.height=lineHeight*textarea.rows+'px';
        return textarea.style.height
    }

5.

juzhiqiang commented 5 years ago

1. let elTextarea = document.getElementsByTagName('textarea')[0]

2.let setRow = elTextarea.setAttribute('row',5)

3.window.getComputedStyle(elTextarea).height

4. let lineH = window.getComputedStyle(elTextarea).lineHeight;
    let getRow = elTextarea.getAttribute('row')
    elTextarea.setAttribute('height',lineH === 'normal' ? parseInt(elTextarea.fontSize) *  getRow : parseInt(lineH) * getRow ) 

5. 利用获取textarea里面的换行符计算有多少哥换行符乘以行高
347235420 commented 5 years ago

1. const text=document.querySelector('textarea') 2. text.rows=5

3. var textHeight=getComputedStyle(text).height 4. var lineHeight=getComputedStyle(textHeight)["lineHeight"]; if(lineHeight == ‘normol’){ lineHeight =1+‘rem'; } text.style.height = parseFloat(textHeight) * text.rows + 'px'; 5.

zhangxinxu commented 5 years ago

本期要点:

  1. document.querySelector;
  2. myTextarea.rows = 5;
  3. window.getComputedStyle(myTextarea).height
  4. IE下textarea的高度不是行高决定的,而是font-size和font-family。
  5. DOMNodeInserted(DOM level 3, IE9+)以及MutationObserver(DOM level 4 IE11+)。前者不是异步的,所以如果有大量的DOM变化和事件处理,性能影响会很明显,MutationObserver则是异步的,先观察,然后一次性处理。 document.addEventListener('DOMNodeInserted', function(event) { if (event.target.nodeName.toLowerCase() === 'textarea') { //... } });