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

 

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>

你可能感兴趣的:(JavaScript)