1. Question
Use JS code to find the final background-color of an element on the page, regardless of the IE browser or the element float situation.
2. Question analysis
1. Examine the underlying JavaScript foundation
In front-end development, the most common thing you are exposed to in daily life is the writing of page styles. Getting rid of tool libraries such as jQuery and using native js to obtain styles is a skill that every front-end programmer must master in the advanced stage.
2. Test the interviewer's meticulous thinking and development experience
If you think that just finding the style after element calculation is too young. The complexity of the page style is always the most heartbreaking. Even if the front-end is so awesome, everyone will be upset when they hear it is compatible with IE6. Therefore, special circumstances must be considered: the values of display, opacity, and visibility.
3. Theoretical basis
1. Inline style
Inline styles can be obtained through the element's style attribute. If the style attribute has a background-color value, it can be obtained directly (not considering!important).
2. Outreach cascading style
DOM2 style specifications areIncluded with onegetComputedStyle()method. This method returns a read-only CSSstyleDeclaration object containing all the computed styles for a specific element.
4. Solve the problem
4.1 Encapsulate all tool methods in WDS (wall dom script) namespace
(function(WDS, undefined){ // Encapsulation code...})( || ( = {}));
The code is encapsulated in the namespace and will not cause unintentional code pollution.
4.2 Tool method camelize
// Convert string to camelfunction camelize(str) { return (/-(\w)/g, function (strMatch, p1){ return (); }); }
This method is independent to facilitate the subsequent writing of getStyle() method.
The function is to convert the css attribute value of the hyphen class into camel writing method.
For example: Convert background-color to backgroundColor
4.3 Get the calculation style of a specific element
// Get the calculated style of the elementfunction getStyle(elem, property){ if(!elem || !property){ return false; } var value = [camelize(property)], // Get whether there is an inline style first css; // All calculation styles obtained // No inline style, get the style calculated by the cascading style sheet if(!value){ if( && ){ css = (elem, null); value = css ? (property) : null; } } return value; }
By doing this, the first inspection point will basically be satisfied. You can also know whether the interviewer has a solid enough JS foundation.
In addition, for example, the judgment of safety protectionif(!elem || !property)and function sniffingif( && ), can well reflect the developer's code logic and development experience.
4.4 Exclude special circumstances
// Check whether the obtained background color is validfunction checkBgValue(elem){ var value = getStyle(elem, 'background-color'), hasColor = value ? true : false; // Is there any color // Exclude special circumstances if(value == "transparent" || value == "rgba(0, 0, 0, 0)"){ // background-color is not set, or is set to follow the parent node hasColor = false; }else if(getStyle(elem, 'opacity') == "0"){ // The transparency of the dom node is fully transparent hasColor = false; }else if(getStyle(elem, 'visibility') == "hidden"){ // The dom node is not visible hasColor = false; }else if(getStyle(elem, 'display') == "none"){ // The dom node is not visible hasColor = false; } return hasColor; }
4.5 Get the color of the div final display on the page
// Get the color of the final display of the divfunction getRealBg(elem){ if(checkBgValue(elem)){ return getStyle(elem, 'background-color'); }else if(elem != ){ return getRealBg(); } return ''; }
Getting style values is processed recursively.
If the element style can be obtained successfully, and it will not be triggered4.4 Exclude special circumstancesOne of them will directly return the result.
If a special case is triggered, you need to find the styles of the parent node and higher-level nodes to obtain the background-color value that can be seen by the naked eye and displayed on the page.
During the upward traceback, if you have already traced back to the html root node, you can stop backtracking. So I added a judgmentelse if(elem != )
5. The missing big boss
5.1 Big boss !important
If you use !important indiscriminately, the maintenance and development of large-scale projects will definitely be a nightmare. Because of the calculation of priority rules, the!important is always at the top of the food chain.
The current question does not consider this situation, which is also my laziness. It's really tricky, so I won't write the code for this logical branch. Here is a reminder~
5.2 The parent and root node of the big boss have set invisible css attributes
Just set the css statement:html {display:none;},All elements of the page disappear immediately. As long as the superior node of any specific element is setopacity,display,visibility, the judgment logic becomes complicated instantly. So, I won’t go to this muddy water O(∩_∩)O Haha~
6. Points of improvement
In fact, I was lazy and did not do the best in the judgment of excluding special circumstances - the rgb color value and specific color value (such as red) did not undergo a unified conversion, but just added a rigid judgment.if(value == "transparent" || value == "rgba(0, 0, 0, 0)")。
If you are interested, you can search for the js method of color value conversion, and I won’t write it here.
7. Source code and demo
Source code address:/wall-wxk/blogDemo/blob/master/2017/02/05/
demo:/blogDemo/2017/02/05/
The above is all the content of this article. I hope that the content of this article will help you study or work. I also hope to support me more!