New Image Replacement Technology: The State scope Method)

Source: Internet
Author: User

Thanks to the translation of the blue ideal dishuipiaoxiang, I learned about this brand new image replacement method. Note: It is an image replacement, but an image rotation. I believe that every web designer will always use it! When we need to use some special fonts for logo, trademark and Banner, in order to solve the problem that the user machine does not have this font, only the image is replaced or the sifr solution is used (@ face and EOT fonts are unreliable). Of course, the former is much more common and easier than the latter. There are many image replacement methods, such as directly hiding text, margin shift, text indent, and container zero-height and zero-width ...... And so on. Below, according to the original translator'sArticleBased on my understanding, I Will retell you how to use this method.

The new method, called the state scope method by the original author Paul Young, has a unique idea and regards the entire document as a state machine, it binds or deletes a class above it by monitoring its status, and this class carries information that shows the background image of a certain area. In other words, this class is added later, but it is much earlier than the general JS dynamic addition, because it is bound to the top-level element HTML! Many people may be confused here, including the original translator, so the example provided by him cannot run. This involves a deep-seated programming philosophy. The original author also talked about the design pattern ...... But it doesn't matter. We can analyze it in detail.

 
H1 {width: 100px; Height: 50px;} @ media screen {. images-on H1 {text-indent:-pixel PX; Background-image: url(image.png); overflow: hidden ;}}

The first CSS rule is always executed. H1 is what we call the area where the background image is to be added. The State scope method is translated as the "State domain method". Although it looks quite tasty, the State scope method is translated as "state Area Method" by Alibaba Cloud ", the status refers to the status of the HTML element, and the region refers to the area where the background image is added. Is it easy to understand !)

The second option is execution. It looks a little complicated. It is enclosed in the @ media screen block. It is used to ensure that image replacement only occurs in the screen reader, rather than in the print status. If this is not done, most users will see a large gap rather than meaningful text during page printing. However, if we do not print it, it will be dispensable, and the demonstration page provided by the original author Paul Young will not have the @ media Screen Block. Aside from @ media screen, we found that
The descendant selector (descendant selectors) is also called a inclusion selector. The key to whether the background information is processed is its (H1) ancestor (. images-on) is there! We can use addclass and removeclass to dynamically add or delete the. images-on class for HTML.

Below is the coreCode:

VaR hasclass = function (Ele, CLS) {return ELE. classname. match (New Regexp ('(\ s | ^)' + CLS + '(\ s | $)');} var addclass = function (Ele, CLS) {If (! This. hasclass (Ele, CLS) ELE. classname + = "" + CLS;} var removeclass = function (Ele, CLS) {If (hasclass (Ele, CLS )) {var Reg = new Regexp ('(\ s | ^)' + CLS + '(\ s | $)'); ELE. classname = ELE. classname. replace (Reg, '') ;}/ *** @ scope is the class for setting how to replace images in a region, is the state of * @ on being an HTML element to be bound to an HTML element. It is used to dynamically bind or delete the scope class above */document. enablestatement= function (scope, on) {var de = document.doc umentelement; on? Addclass (De, scope): removeclass (De, scope );};

The remaining problem is how to monitor the status of HTML elements or determine the status of HTML elements. This implementation is really clever. It assigns a true or false value to on by detecting the onerror event of the image object (based on the event propagation mechanism of JavaScript, most low-level events of sub-elements will bubble to the upper-level elements until the top-level elements. If this element also has the ability to process this event, it will be executed ). Obviously, onerror is a very primitive event. If an error occurs in one place, the entire document will report an error. According to our above formulation, the onerror state of the image object is the state of the HTML element and the status of the HTML element can be determined far from the element where the background image is located by traversing the DOM tree, make a quick decision again!

Since it is an image object detection, we first need to know whether this element exists, but we do not check whether it exists on the server side, which will lead to an additional HTTP request. The author created a clever method.

In most browsers, the image object can be instantiated and an invalid URL (http: // 0) will be automatically appended. Through this, we can easily determine whether the image is available. If this is the case, the onerror event will be triggered, so we will set on to false, otherwise it will be true. In this case, we can dynamically create an image object in Js.

 
VaR IMG = new image ();

However, two browsers are not compatible with this method. In gecko kernel browsers (such as ff), the onerror event is always triggered no matter whether the image is available or not, so our original judgment scheme won't work. Fortunately, we found another method. We may add an invalid background image to the HTML element and use the getcomputedstyle method to obtain its style. backgroundimage value. If the image is unavailable, the value is none or URL (invalid-URL :). In this case, we can safely set on to false!

If (IMG. style. constraint binding! = NULL) {/* determine whether it is Firefox * // * forcibly sets the image URL to http: // 0 */IMG. style. backgroundimage = "URL (" + document. location. protocol + "// 0)";/* obtain the final result value of the element applied to the page in the style sheet */var BG = Window. getcomputedstyle (IMG ,''). backgroundimage; If (BG! = "NONE" & BG! = "URL (invalid-URL :)" | document. URL. substr (0, 2) = "fi") {/*** if the image URL value is not none or URL (invalid-URL :), or the address bar is not file: /// * set on to true */document. enablestattings ("images-on", true );}}

Another challenging browser is safari. If the request is an invalid URL, an error message will be displayed in the safari status bar, but the page layout is not affected. If the user's status bar is enabled, the error will continue, which is not professional. Therefore, the author proposes another feasible solution. A 1*1 GIF image is dynamically generated using base64 encoding to prevent continuous error reporting. If an image is unavailable, its width will be zero. We may use it as our criterion.

If (IMG. style. constraint binding! = NULL) {/* determine if it is Firefox * // ************************/} else {img.style.css TEXT = "-WebKit-opacity: 0 "; if (IMG. style. webkitopacity = 0) {/* determine whether it is safari */IMG. onload = function () {/* If the image width is less than zero, it indicates that the image is available. We set on to true; otherwise, it is false */document. enablestattings ("images-on", IMG. width> 0);}/* dynamically generate GIF images to prevent errors because the images do not exist! */IMG. src = "data: image/GIF; base64," + "r0lgodlhaqabaiaaap // waaach5bae" + "aaaaalaaaaaabaaeaaaicraeaow = ";}}

Finally, when initializing an image object in other browsers, you only need to check whether the onerror event occurs.

If (IMG. style. constraint binding! = NULL) {/************************/} else {If (IMG. style. webkitopacity = 0) {/*************************/} else {IMG. onerror = function (e) {document. enablestattings ("images-on", true);}/* cancel onerror event */IMG. src = "about: blank ";}}

The complete method is provided below, and the closure is used to keep the enablestatescope method available all the time!

 (function () {d1_document1_e1_d.doc umentelement; C = "images-on "; I = new image (); t = I. style; S = D. enablestatescope = function (s, O) {If (o) E. classname + = "" + S; else E. classname = E. classname. replace (New Regexp ("\ B" + S + "\ B"), "") ;}; if (T. invalid binding! = NULL) {T. backgroundimage = "URL (" + D. location. protocol + "// 0)"; B = Window. getcomputedstyle (I ,''). backgroundimage; If (B! = "NONE" & B! = "URL (invalid-URL :)" | D. URL. substr (0, 2) = "fi") S (C, true);} else {t.css text = "-WebKit-opacity: 0"; if (T. webkitopacity = 0) {I. onload = function () {S (C, I. width> 0) ;}; I. src = "data: image/GIF; base64, r0lgodlhaqabaiaaap // waaach5baeaaaaalaaaabaaeaaaicraeaow =";} else {I. onerror = function () {S (C, true) ;}; I. src = "about: blank" ;}}) (); 

<Br/> <! Doctype HTML> <br/> <HTML dir = "LTR" lang = "ZH-CN"> <br/> <pead> <br/> <meta charset = "UTF-8" /> <br/> <meta http-equiv = "X-UA-compatible" content = "Ie = edge"> <br/> <style type = "text/CSS"> <br/> </style> <br/> <SCRIPT type = "text/JavaScript">/* <! [CDATA [*/<br/> var hasclass = function (Ele, CLS) {<br/> return ELE. classname. match (New Regexp ('(\ s | ^)' + CLS + '(\ s | $ )')); <br/>}< br/> var addclass = function (Ele, CLS) {<br/> If (! This. hasclass (Ele, CLS) ELE. classname + = "" + CLS; <br/>}< br/> var removeclass = function (Ele, CLS) {<br/> If (hasclass (Ele, CLS )) {<br/> var Reg = new Regexp ('(\ s | ^)' + CLS + '(\ s | $)'); <br/> ELE. classname = ELE. classname. replace (Reg, ''); <br/>}< br/> // don't copy and paste this code, use the minified script <br/> document. enablestattings = function (scope, on) {<br/> var de = document. do Cumentelement; <br/> on? Addclass (De, scope): removeclass (De, scope); <br/>}; <br/> (function () {<br/> var de = document.doc umentelement; <br/> var IMG = new image (); <br/> // processing of the gecko kernel browser <br/> If (IMG. style. invalid binding! = NULL) {<br/> IMG. style. backgroundimage = "URL (" + document. location. protocol + "// 0)"; <br/> var BG = Window. getcomputedstyle (IMG ,''). backgroundimage; <br/> // If images is off, the BG value in ff2 and earlier versions is "NONE" <br/> // In ff3, the BG value is "URL (invalid-URL :)" <br/> If (BG! = "NONE" & BG! = "URL (invalid-URL :)" | document. URL. substr (0, 2) = "fi") {<br/> document. enablestat ("images-on", true); <br/>}< br/>}else {<br/> // applicable to Safari browser (including iPhone) <br/> img.style.css text = "-WebKit-opacity: 0"; <br/> If (IMG. style. webkitopacity = 0) {<br/> IMG. onload = function () {<br/> document. enablestattings ("images-on", IMG. width> 0); <br/>}< br/> // source the image to a 43-byte 1x1 p Ixel GIF image encoded as a data Uri. <br/> IMG. src = <br/> "data: image/GIF; base64," + <br/> "r0lgodlhaqabaiaaap // waaach5bae" + <br/> "aaaaalaaaabaaeaaaicraeaow = "; <br/>} else {// handling for everything else <br/> IMG. onerror = function (e) {<br/> document. enablestattings ("images-on", true); <br/>}< br/> IMG. src = "about: blank"; <br/>}< br/> })(); <br/> //]> <br/> </SCRIPT> <br/> <Script Type = "text/JavaScript" >/// <! [CDATA <br/> window. onload = function () {<br/> document. enablestattings ("images-on", false); <br/>}< br/> // Toggles the images-on State scope on and off, <br/> // and displays the appropriate message <br/> function toggle (on) {<br/> document. enablestattings ("images-on", on); <br/> document. getelementbyid (on? "Statescopeon": "statescopeoff"). style. Display = "Block"; <br/> document. getelementbyid (on? "Statescopeoff": "statescopeon "). style. display = "NONE "; <br/>}< br/> //]> <br/> </SCRIPT> <br/> <style type = "text/CSS"> <br/>. width {<br/> width: 800px; <br/> margin: auto; <br/> text-align: Left; <br/>}< br/>. header H1 {<br/> margin-top: 10px; <br/> margin-bottom: 25px; <br/> color: White; <br/> line-height: 1; <br/> top:-35px; <br/> font-size: 9pt; <br/> text-transform: uppercase; <br/>} <Br/>. header H1. statement{ <br/> color: # abdda9; <br/> letter-Spacing:-2px; <br/> text-transform: none; <br/> font-size: 35pt; <br/> top: 0.52em; <br/>}</P> <p>. images-on. header H1 {/* use images-on to monitor the H1 style */<br/> text-indent:-12345px; <br/> overflow: hidden; <br/> Background: URL (http://images.cnblogs.com/cnblogs_com/rubylouvre/199042/o_aggregated.png) No-Repeat; <br/> width: 297px; <br/> H Eight: 66px; <br/> top: 0; <br/>}</P> <p>/* toggle switch */<br/> # statescopeoff, # statescopeon {<br/> position: absolute; <br/> top:-1px; <br/> right: 25px; <br/> background-color: white; <br/> padding: 9px 15px; <br/> border: 1px solid # 79b17c;/* [e] 1px solid @ 00 */<br/> font-size: 10pt; <br/> Z-index: 1; <br/>}< br/> # statescopeon {<br/> display: none; <br/>}</P> <p> </style> <br/> </pead> <br /> <Body> <br/> <Div class = "width"> <br/> <Div class = "Header"> <br/> <p> the <SPAN class = "statscope"> state scope </span> </p> <br/> </div> <br/> <Div id =" statescopeoff "> currently, the images-on class <strong> does not exist. </Strong> <a href = "javascript: toggle (true)"> Add it? </A> </div> <br/> <Div id = "statescopeon"> the images-on class <strong> already exists. </Strong> <a href = "javascript: toggle (false)"> delete it? </A> </div> <br/> </body> <br/> </ptml> <br/>

Run code

Http://www.denisdeng.com/exzample/state-scope-image-replacement.html

Some advantages of this method

    • When the client computer does not support JavaScript or image display, it can be elegantly degraded, not due to the difference in page effects.
    • Support for translucent or transparent Images
    • The implementation is very simple. You only need to import our script and set the region where the image needs to be replaced.
    • Because it uses a very basic technology, it is even smooth in the air Browser
    • Compliant with standards and friendly to screen readers and search engines
    • No additional tags required
    • No memory consumption (because the DOM tree is basically not traversed)
    • Even after a page is loaded, Dom operations will not affect its effect.
    • The loading process will not trigger or only Flash slightly.
    • Text and image can be centered or left aligned in the container element settings
    • A 1*1 GIF image is not required on the server to prevent errors.
    • Display on display and print pages
    • Because the CSS background-image attribute is used to set images, we can use the image sprites technology to reduce the number of requests.

Attached the original article by Paul Young:
Http://www.sitepoint.com/article/image-replacement-state-scope/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.