获取元素的值一次,然后保持该值为静态

Get value of element once then keep that value static

本文关键字:然后 静态 元素 获取 一次      更新时间:2023-09-26

我正在使用

function expand(btn) {
var box = btn.parentNode.parentNode,
    ipsum = box.getElementsByTagName("p")[0],
    textSize = window.getComputedStyle(ipsum, null).getPropertyValue('font-size'),
    lineHeight = window.getComputedStyle(ipsum, null).getPropertyValue('line-height'),
    boxWidth = window.getComputedStyle(box, null).getPropertyValue('width'),
    initialHeight = window.getComputedStyle(box, null).getPropertyValue('height'),
    numText = parseInt(textSize),
    numWidth = parseInt(boxWidth),
    numHeight= parseInt(initialHeight);

if(box.style.height == "150px"){
    box.style.height = "40px";
    ipsum.style = "display:none";
}
else{
    box.style.height = "150px";
    ipsum.style = "display:inline";
}
console.log(lineHeight);
}

要得到一个元素的初始高度值,唯一的问题是元素高度经常变化,但得到的第一个值总是正确的,我如何才能得到初始值并保持它不变?如何只在变量中存储一次值,我需要在变量中进行计算,但由于值不断变化,我得到了错误的数字输出。

您可以重构函数,以便在首次运行时将initialHeight存储在"私有"变量中:

var expand = (function() {
    var initialHeight;
    // Return a function that holds initialHeight in a closure
    return function (btn) {
      // Get box before setting/getting initialHeight
      var box = btn.parentNode.parentNode;
      // Set initialHeight only if undefined
      initialHeight = initialHeight || window.getComputedStyle(box, null).getPropertyValue('height');
      // Do other variables
      var ipsum = box.getElementsByTagName("p")[0],
          textSize = window.getComputedStyle(ipsum, null).getPropertyValue('font-size'),
          lineHeight = window.getComputedStyle(ipsum, null).getPropertyValue('line-height'),
          boxWidth = window.getComputedStyle(box, null).getPropertyValue('width'),
          numText = parseInt(textSize),
          numWidth = parseInt(boxWidth),
          numHeight= parseInt(initialHeight);
      if(box.style.height == "150px"){
        box.style.height = "40px";
        ipsum.style.display = "none";
      } else {
        box.style.height = "150px";
        // If ipsum is a P, probably better to use "" (empty string) here
        // so it returns to its default or inherited value
        // ipsum.style.display = "inline";
        ipsum.style.display = "";
      }
      console.log(lineHeight);
    }
}());

以上是一个适当的重构,使用以下标记进行了测试:

<style type="text/css">
#box {border: 1px solid blue;}
#notBox {border: 1px solid red;}
#ipsum {border: 1px solid yellow;}
</style>
<div id="box">box
  <div id="notBox">notBox
    <input type="button" onclick="expand(this)" value="Expand&hellip;">
    <p id="ipsum">ipsum</p>
  </div>
</div>

你能把它设置为一个属性吗?类似于:

// set the value once some place
box.setAttribute('data-init-height', window.getComputedStyle(…)… );
// when setting the initial height, check for the attribute first
initialHeight = box.getAttribute('data-init-height') || window.getComputedStyle(…)…;

跟进:请参阅fiddle

每次执行函数expand时,initialHeight都会得到一个新值。您所需要的只是将其记录在一个闭包中,如果您要处理的btn超过1,则使用哈希;如果您想为每个btn记录多个高度,则使用数组进行赋值。就像这样:

// predefine the function expand for furthre usage.
var expand;
(function() {
    /* 
    having arrays as value, indexed like this:
    {
        <btn_1_id> : [<firstHeight>, <2nd Height>, ...],
        <btn_2_id> : [],
        ...
    }
    */
    // Let's assume every btn is having an id. You may think another way yourself it they don't.
    var initialHeightForMultiBtns = {};
    expand = function(btn) {
        // ...blablabla
        initialHeightForMultiBtns[btn.id] = initialHeightForMultiBtns[btn.id] || [];
        initialHeightForMultiBtns[btn.id].push(window.getComputedStyle(box, null).getPropertyValue('height'));
        console.log(initialHeightForMultiBtns[btn.id][0]); // the real initialized height for the given btn.
        // ...blablabla
    }
})()
expand(btn_1); // let's expand btn_1 here.

祝你好运。