javascript - trick to set/get attributes that expects px values

本文介绍了一个JavaScript函数,用于为HTML元素设置CSS样式属性时自动添加像素单位。文章通过实例展示了如何使用该函数来确保跨浏览器兼容性,并正确地设置顶部和左侧偏移。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

When setting a number into a style property you must specify the unit in order for it to work across all browsers.

 

 

<html>
<head>
<title>Pixel Style Test</title>
<script type="text/javascript">
  (function () {
    // setting of numbers to properties that normal consume pixels, you have to append the unit, in this case, it is the px itself.
    var check = /z-?index|font-?weight|opacity|zoom|line-?height/i;
    this.pxStyle = function (elem, name, value) {
      var nopx = check.test(name);
      if (typeof value !== "undefined") {
        if (typeof value === "number") {
          // when you set the number to attribute of Style that expects some px unit, you should append "px" to the end. 
          value += nopx ? "" : "px";
        }
        elem.style[name] = value;
      }
      return nopx ?
        elem.style[name] :
        // always return the value parseFloat.
        parseFloat(elem.style[name]);
    };

  })();

</script>
  <script type="text/javascript">
    window.onload = function () {
      var elem = document.getElementById("div");
      alert
      pxStyle(elem, "top", 5);
      // Alerts out '5'
      alert(pxStyle(elem, "left"));
    };
  </script>
</head>
<body>
 <div style="top:10px;left:5px;" id="div" ></div>

</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值