When we operate css styles through javascript, if we stay at the css2 stage, we will find that it is not very difficult to operate. Although there are some browser compatibility issues, by encapsulating our own functions, we can not only set styles but also obtain styles. However, what will happen if javascript encounters css3?
We know that although CSS3 currently appears in various browsers, it has not yet been officially released as a set of specifications. Therefore, each browser has different support for CSS3 attributes. Hence the term "css Hack". Great, why? Because through css Hack we can be compatible with various browsers at the css level, and there is no need to borrow javascript to achieve it. But the five major browsers have their own Hack headers (Safari and chrome are: webkit. IE is: ms. Opera is: o. Firefox is: moz). This also creates a certain degree of code redundancy. And when we control css3 attributes through js, another problem arises.
The problem that arises this time is not difficult. In the final analysis, it is a problem of code redundancy (because we have to set styles for 4 mainstream kernels respectively), so let’s solve this problem through functions:
1 function setHack(ele,attr) { 2 //利用for-in循环遍历attr里面的属性 3 for (var i in attr){ 4 var newi = i; 5 //遍历是不是有- 6 if(newi.indexOf("-")>0) { 7 var num = newi.indexOf("-"); 8 newi = newi.replace(newi.substr(num,2),newi.substr(num+1,1).toUpperCase()); 9 }10 //常规的设置属性的方式11 ele.style[newi] = attr[i];12 newi = newi.replace(newi.charAt(0),newi.charAt(0).toUpperCase());13 ele.style["webkit" + newi] = attr[i];14 ele.style["moz" + newi] = attr[i];15 ele.style["ms" + newi] = attr[i];16 ele.style["o" + newi] = attr[i];17 }18 }
Function description: The setHack function has two parameters: ele represents which element you want to set attributes for, attr is a json format that contains the attributes and attribute values you set. , such as {"transform":"rotate(20deg)","transform-origin":"120px 120px"}. The if judgment in the code is mainly to change the "-" in the attribute into the format of uppercase letters. The latter is mainly about adding the core part of the Hack header.