Using javascript to generate two-dimensional code images of the current blog address

Posted by Fahid on Sat, 29 Jun 2019 19:33:02 +0200

Previous remarks

A good blog post was found on the computer and wanted to be accessed on the mobile phone. At this point, you have to open the mobile browser to enter long ones. URL Address is OK. It's very inconvenient. If the blog title is followed by a small picture, click on the picture, a two-dimensional code of the big picture appears, and then through the mobile phone sweep, to visit the blog, it is relatively convenient.

Searching through search engines for articles that generate two-dimensional codes, it is not easy to find them. At the same time, it is also found that qrcode plug-in The plug-in is specially designed to generate two-dimensional codes. Therefore, based on qrcode, a two-dimensional code plug-in qr is implemented.

 

Demonstration of effect

If you are careful, you will find that the title of the blog is followed by a small icon of a cell phone that represents a two-dimensional code. After clicking on the icon, a two-dimensional code map appears, which can be scanned by the mobile phone to access the web page. After clicking on the small icon or two-dimensional code picture, the two-dimensional code picture disappears.

I named the plug-in qr.js The way to use it is very simple, as long as the following introduction can be made

<script src="http://files.cnblogs.com/files/xiaohuochai/qr.js"></script>

 

Explanation of Principle

1. Firstly, the HTML structure of blog park is analyzed.

As can be seen from the figure above, the blog posts in the blog Garden are located in the div of the class'post', the outer layer is the div of the id name'topics', and the title of the blog posts is located in h1 of the class'postTitle'. So when the page structure is loaded, you can add pictures to the back of the title.

var oBox = document.getElementById('topics');
var oTitle = oBox.getElementsByTagName('h1')[0];
console.log(oTitle.innerHTML);         

 

2. Generation of Two-Dimensional Code Graph

Now, you need to prepare a two-dimensional code map and insert it after the title of the blog post.

Adoption iconfont Find a two-dimensional code map, which is shown below. Because it is convenient for mobile terminals to use, it uses an icon to represent a `small cell phone'.

Then the picture will be processed. base64 encoding

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAoklEQVQ4T+2T4Q2CMBCFv27CBjgCG+gIjAAbOAIjOIJs4Ai6gRvIBpjXXCOp19T/8pJLoTneXcj3Ah91wAV4bu68xwXoAZ2EzEAmE9AWTB6AelRDyaAx9zgh0wE4ATczcTdIE7wl0oe7wX/8RMHigfQTB3fDdM1IEvYyONdIVEOSqDwCY2Z2NaS/UNbqMSQmvauUPlfbNKpBSdTUVyXSs/XyBlRCNBG20I28AAAAAElFTkSuQmCC

By looking at the style, the skin used sets the margin attribute on the img title, as shown below

So, we need to set margin 0 here.

var oBox = document.getElementById('topics');
var oTitle = oBox.getElementsByTagName('h1')[0];
var oImg = new Image();
oImg.id = 'oImg';
oImg.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAoklEQVQ4T+2T4Q2CMBCFv27CBjgCG+gIjAAbOAIjOIJs4Ai6gRvIBpjXXCOp19T/8pJLoTneXcj3Ah91wAV4bu68xwXoAZ2EzEAmE9AWTB6AelRDyaAx9zgh0wE4ATczcTdIE7wl0oe7wX/8RMHigfQTB3fDdM1IEvYyONdIVEOSqDwCY2Z2NaS/UNbqMSQmvauUPlfbNKpBSdTUVyXSs/XyBlRCNBG20I28AAAAAElFTkSuQmCC";
oImg.style.margin = '0';
oTitle.appendChild(oImg);        

 

3. Converting the URL of the web page into two-dimensional code

Getting a URL is very simple, as long as you use it location object The href attribute of

Next, use QRCode plug-in To realize the function of converting URL s into two-dimensional codes, download them first. qrcodejs plug-in Then the URL of the blog post is converted to a custom size two-dimensional code

<div id="qrcode"></div>
<script src="http://files.cnblogs.com/files/xiaohuochai/qrcode.min.js"></script>
<script type="text/javascript">
var qrcode = new QRCode(document.getElementById("qrcode"), {
    text: location.href,
    width: 80,
    height: 80
});
</script>

Generate a two-dimensional code picture as shown in the following figure

4. Dynamic Generation and Mouse Click Events

Since the final encapsulation is in a js file, the HTML structures involved in the third step need to be dynamically generated

Since the generation of two-dimensional codes depends on the qrcodejs plug-in, only when the plug-in is loaded, can the subsequent operation be carried out. script tag Support load event But it is not compatible with IE8-browser. So, the safer way is to use window.onload

After clicking on the logo image, the generated two-dimensional code image is displayed on the right side of the logo image. Since the two-dimensional code image is equivalent to the absolute positioning of the image, it is necessary to change the HTML structure and add a div of oImgBox to the outer layer of the small logo image to locate the large two-dimensional code image.

//Get the title of the blog post
var oBox = document.getElementById('topics');
var oTitle = oBox.getElementsByTagName('h1')[0];

//Create logo pictures and outer packaging div
var oImgBox = document.createElement('div');
oImgBox.style.cssText = 'position:relative;display:inline-block;vertical-align:middle';
var oImg = new Image();
oImg.id = 'oImg';
oImg.style.cursor = 'pointer';
oImg.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAoklEQVQ4T+2T4Q2CMBCFv27CBjgCG+gIjAAbOAIjOIJs4Ai6gRvIBpjXXCOp19T/8pJLoTneXcj3Ah91wAV4bu68xwXoAZ2EzEAmE9AWTB6AelRDyaAx9zgh0wE4ATczcTdIE7wl0oe7wX/8RMHigfQTB3fDdM1IEvYyONdIVEOSqDwCY2Z2NaS/UNbqMSQmvauUPlfbNKpBSdTUVyXSs/XyBlRCNBG20I28AAAAAElFTkSuQmCC";
    oImg.style.margin = '0';
    oImgBox.appendChild(oImg);
    //Insert the logo image after the title
oTitle.appendChild(oImgBox);    

//Dynamic Generation script Label, Introduce qrcode Plug-in unit
var script = document.createElement("script");
script.type = "text/javascript";
script.src = 'http://files.cnblogs.com/files/xiaohuochai/qrcode.min.js';
document.body.appendChild(script);

//Dynamic Generation div Label for placing through qrcode Plug-in generated two-dimensional code maps, hidden by default display
var oDiv = document.createElement('div');
oDiv.id = 'qrcode';    
oDiv.mark = false;
oDiv.style.cssText = 'display:none;position:absolute;left:20px;top:-40px';
oImgBox.appendChild(oDiv);        
window.onload = function(){
    new QRCode(oDiv, {
        text: location.href,
        width: 80,
        height: 80
    });            
}

//Mouse into the outer layer of the logo picture oImgBox After that, the two-dimensional code picture is displayed on the right side of the identifying picture.
oImgBox.onclick = function(){
    //If mark To be true, show that the two-dimensional code picture is being displayed and hide it
    if(oDiv.mark){
        oDiv.style.display = 'none';
    //Otherwise, the two-dimensional code picture is hidden and displayed.
    }else{
        oDiv.style.display = 'block';
    }
    //take mark Identity reversal
    oDiv.mark  = !oDiv.mark;    
}

 

5. Mobile optimization

Since this function is only applicable to the computer side, it has no practical use in the mobile side. So, through User Agent Detection If it is a non-mobile terminal, the above operation is performed

Because other plug-ins may also use window.onload, to avoid conflicts, use compatible event handler functions

The optimized final code is as follows

(function(){
    //Event Handler Compatible Writing
    function addEvent(target,type,handler){
        if(target.addEventListener){
            target.addEventListener(type,handler,false);
        }else{
            target.attachEvent('on'+type,function(event){
                return handler.call(target,event);
            });
        }
    }
    function whichMobile(){
        var ua = navigator.userAgent;
        if(/iPhone OS (\d+_\d+)/.test(ua)){
            return 'iPhone' + RegExp.$1.replace("_",".");
        }
        if(/iPad.+OS (\d+_\d+)/.test(ua)){
            return 'iPad' + RegExp.$1.replace("_",".")
        }
        if(/Android (\d+\.\d+)/.test(ua)){
            return 'Android' + RegExp["$1"];
        }
    }    
    //If it's a non-mobile end, execute the following code
    if(!whichMobile()){
        //Get the title of the blog post
        var oBox = document.getElementById('topics');
        var oTitle = oBox.getElementsByTagName('h1')[0];

        //Create logo pictures and outer packaging div
        var oImgBox = document.createElement('div');
        oImgBox.style.cssText = 'position:relative;display:inline-block;vertical-align:middle';
        var oImg = new Image();
        oImg.id = 'oImg';
        oImg.style.cursor = 'pointer';
        oImg.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAoklEQVQ4T+2T4Q2CMBCFv27CBjgCG+gIjAAbOAIjOIJs4Ai6gRvIBpjXXCOp19T/8pJLoTneXcj3Ah91wAV4bu68xwXoAZ2EzEAmE9AWTB6AelRDyaAx9zgh0wE4ATczcTdIE7wl0oe7wX/8RMHigfQTB3fDdM1IEvYyONdIVEOSqDwCY2Z2NaS/UNbqMSQmvauUPlfbNKpBSdTUVyXSs/XyBlRCNBG20I28AAAAAElFTkSuQmCC";
            oImg.style.margin = '0';
            oImgBox.appendChild(oImg);
            //Insert the logo image after the title
        oTitle.appendChild(oImgBox);    

        //Dynamic Generation script Label, Introduce qrcode Plug-in unit
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = 'http://files.cnblogs.com/files/xiaohuochai/qrcode.min.js';
        document.body.appendChild(script);

        //Dynamic Generation div Label for placing through qrcode Plug-in generated two-dimensional code maps, hidden by default display
        var oDiv = document.createElement('div');
        oDiv.id = 'qrcode';    
        oDiv.mark = false;
        oDiv.style.cssText = 'display:none;position:absolute;left:20px;top:-40px';
        oImgBox.appendChild(oDiv);    

        addEvent(window,'load',function(){
            new QRCode(oDiv, {
                text: location.href,
                width: 80,
                height: 80
            });                  
        })

        //Mouse into the outer layer of the logo picture oImgBox After that, the two-dimensional code picture is displayed on the right side of the identifying picture.
        addEvent(oImgBox,'click',function(){
            //If mark To be true, show that the two-dimensional code picture is being displayed and hide it
            if(oDiv.mark){
                oDiv.style.display = 'none';
            //Otherwise, the two-dimensional code picture is hidden and displayed.
            }else{
                oDiv.style.display = 'block';
            }
            //take mark Identity reversal
            oDiv.mark  = !oDiv.mark;                
        })
    }
})();

Topics: Javascript QRCode Mobile Attribute