访问CSS高度值(通用方法)

Accessing CSS height value (universal method)?

本文关键字:方法 CSS 高度 访问      更新时间:2023-09-26

我需要知道是否有可能让这个代码片段的heightVal变量通用。这意味着我需要它访问我作为box参数传入的任何元素的高度,并存储它,以便可以使用它将元素重置为其原始高度。使用offsetHeight属性对我不起作用,因为当第二次访问该函数时,该值会自动重置。(我试图使这个函数普遍适用于任何元素)。

function expand(box){
  var heightVal = document.styleSheets[0].cssRules[3].style.height;
  if(box.style.height != "20px"){
    box.style.height = "20px";
  }
  else{
    box.style.height = heightVal;
  }
}

为什么不将其作为属性存储在DOM节点上?

不要执行var heightVal =,而是执行box.my_height =。或者,如果你真的不喜欢HTML5data-XXX只在JS中使用,你甚至可以使用它。

function expand(box){
  if(box.style.height != "20px"){
    box.my_old_height = box.style.height;
    box.style.height = "20px";
  }
  else{
    box.style.height = box.my_old_height;
  }
}