Hands with you to achieve js css property with native set and get

The blog post describes getComputedStyle method, then, we have to implement a simple version of a small plug-in, enables to get and set css properties, without the aid of jQuery.

Author: Icarus
original link: hands with you to achieve js css property with native set and get

Let's start

First, create a css-tool.jsfile, first he looks like this:

;(function (window,undefined) {
  "use strict";

  var cssTool = function () {
    return new cssTool.prototype.init();
  }

  cssTool.prototype = {
    init: function() {
      console.log('init success');
      return this;
    },
  }

  cssTool.prototype.init.prototype = cssTool.prototype;
  // 暴露接口
  window.cssTool = cssTool;

})(window);

Global scope can be seen as an apartment building, we create an anonymous function is executed immediately, the equivalent of an apartment building in the apartment, we do things in the house are hidden, that is, for isolation the role of the domain, to avoid conflicts and external variables. Put windowas an argument to get to the house, the future will not go out looking to repeat windowto use. Front of the semicolon in order to guarantee a syntax error in the file and compresses. undefinedNot supported in older browsers, so taking into account the compatibility add a parameter.

We created a called cssToolprivate method, we find the equivalent of a small room in the house to put getand setother methods. Next we add on a prototype initmethod for initialization. Then we modeled jQuerythe way, initthe prototypepoint cssToolis prototype, so we use initwhen creating instance as a constructor, you can have two ways of calling the plug-ways:

  • var ct = new cssTool()Construction of cssToolinstances

  • Direct call cssTool(), return the same cssToolinstance

get method

Common way

Modern browsers and IE9 +

window.getComputedStyle(elem,null).getPropertyValue(attr)

IE678

elem.currentStyle.getAttribute(camelCase(attr))

Compatible processing

Hump ​​nomenclature conversion -camelCase

For currentStyle, in the IE6 browser, he is very single-minded, just like variables hump nomenclature, and IE78 in a little fast and loose, hump nomenclature and the intermediate zone '-' are completely and to be compatible and easy to operate, we convert hump unified nomenclature.

/**
 * 驼峰命名法转换,IE678使用
 * font-size --> fontSize
 * @param {String} attr
 * @param {String} match  匹配到的字符串,如-c
 * @param {String} originText (\w)是一个捕获,这里是捕获到的字符,如c
 * @return 返回驼峰命名方式的css属性名
 */
function camelCase (attr){
  return attr.replace(/\-(\w)/g, function (match,originText) {
    return originText.toUpperCase();
  });
}

Transparency get -getFilter

IE678 transparency is achieved by filter:alpha(opacity=0)setting, we use regular expression matching to transparency values at this time, since the value obtained at this time is between 0-100, it is necessary in terms of our common form of 0-1.

/**
 * IE678下获取透明度的值
 * @param  elem 获取值的 dom
 * @return {Number} 透明度的值,默认为1
 * IE678下设置透明度 filter: alpha(opacity=0) 取值为0-100
 */
function getFilter(elem) {
  var _filter = elem.currentStyle.getAttribute('filter').match(/alpha\(opacity=(.*)\)/i);
  var value = parseFloat(_filter[1]);
  if(!isNaN(value)){
    // 转化为0-1
    return value ? value/100 : 0;
  }
  return 1;
}

Gets the value of float

The blog suggests, as floatis a reserved word of ECMAScript. So in the browser will have a substitute wording, such as in modern browsers cssFloat, and is in the IE678 styleFloat. After testing, use directly in the modern browsers getPropertyValue("float")can also get the floatvalue. The IE678 is not, so for float, requires a simple hack.

width | height styles acquisition

For a wide elements is not set high, the value obtained directly acquired at IE678 is auto. The modern browser will direct return its value px, our goal is to be returned px value in IE.

// 直接获取外部样式表未设置的 width 和 height 返回值为 auto
// 为了获取精确的 px 值,使用 getBoundingClientRect 方法
// getBoundingClientRect 可以获得元素四个点相对于文档视图左上角
// 的 top、left、bottom、right值,进行简单计算即可
var condition = attr === 'width'
             || attr === 'height'
             && elem.currentStyle[attr] === 'auto';
if(condition){
  var clientRect = elem.getBoundingClientRect();
  return (attr === 'width' ?
          clientRect.right - clientRect.left :
          clientRect.bottom - clientRect.top
         ) + 'px';
}

set method

Compared to the method set methods to get more simple, because we have cssTextthis cross browser IE6 + and modern artifacts.
By elem.style.cssTextmay write to the style element, the operation is actually on the html tag styleattribute. Therefore it can not be directly assigned or lose the entire stylevalue of the property to cover out. We use cumulative way to modify properties.
In addition, there is a small pit IE browser, if cssText not empty, the return value of the last semicolon is deleted, so we need to add a semicolon in front of accumulated property.

/**
 * 设置元素css样式值
 * @param elem 设置值的dom元素
 * @param {String} attr 设置样式名称,如font-size
 * @param {String} value 设置样式的值,如16px
 */
set: function (elem, attr, value){
  // IE78 设置透明度需特殊处理
  if(attr === 'opacity'){
    // 针对 IE7 的 hack
    // filter 滤镜要求 hasLFooout=true 才能执行
    // IE浏览器且 hasLFooout=false 时执行
    if(!!elem.currentStyle && !elem.currentStyle.hasLFooout){
      elem.style.zoom = 1;
      attr = 'filter';
      value = 'alpha(opacity=' + value * 100 + ')';
    }
  }
  // 通用方式
  elem.style.cssText += ';' + (attr + ':' + value) + ';';
}

supplement

Simple Explanation of the effect of the new operator

var Foo = function() {
  return new Foo.prototype.init();
}

Foo.prototype = {
  init: function() {
    this.age = 18;
    return this;
  },
  age: 20
}

console.log(Foo().age); // 18
console.log(Foo.prototype.age); // 20
var Foo = function() {
  return Foo.prototype.init();
}

Foo.prototype = {
  init: function() {
    this.age = 18;
    return this;
  },
  age: 20
}

console.log(Foo().age); // 18
console.log(Foo.prototype.age); // 18

When using the new operator, is put initas a constructor to call, in initwill create an implicit within the object and used thisto it, at this time this.age=18represents an additional age attribute on this implicit objects, the last return thisis not required, the constructor default return this. At this point Foo.prototype.ageit is not affected.
When not using the new operator, the function call corresponds to a normal object, thispoints to initthe object belongs, i.e. Foo.prototype, this.age=18equivalent to Foo.prototype.agethe assignment, and the use of the new operator is essentially different.

summary

Here, the tutorial will also come to an end. A common jQuery css()behind method covers a lot of knowledge, focusing on cross-browser compatibility is what we discussed this, this is just to achieve a very simple operation css plugins. Knowledge still shallow, if there are not clear or the wrong place, welcome to leave a message or mention issue to help me improve this widget.
Finally, the complete project Address: HTTPS: //github.com/xdlrt/css -...
seeking a wave of star ~

Guess you like

Origin www.cnblogs.com/jlfw/p/12554123.html