微信的网站开发教程 (微信网页开发案例)

复盘是一个好的习惯

1、通用函数的封装!

2、flex在移动端的布局

2.2 、css使点击事件失效

pointer-events:none;

3、php常用语法的熟悉情况

https://www.runoob.com/php/php-tutorial.html

  • 变量超过8个显示...
  <?php echo mb_strlen($userInfo['nickname'],'utf-8') > 8 ? '...':'';?>2、最多显示8个长度名字  <?php echo mb_substr($userInfo['nickname'],0,8,'utf-8')?>3、if循环格式  <?php if ($question['answer_num'] == '6') {?>                    AI之星                    <?php }elseif ($question['answer_num'] >= '3' && $question['answer_num'] <= '5') {?>                    AI勇士                    <?php }else{?>                    AI学者                <?php }?>
  • 最多显示8个长度名字
<?php echo mb_substr($userInfo['nickname'],0,8,'utf-8')?>
  • 当前的时间戳
<input type="hidden" name="nowtime" value="<?php echo  time() ?>" >
  • if循环格式
<?php if ($question['num'] == '6') {?>
    明星
    <?php }elseif ($question['num'] >= '3' && $question['num'] <= '5') {?>
    勇士
    <?php }else{?>
    学者
<?php }?>
  • foreach 循环
<?php if ($question_list) {?>
    <?php foreach ($question_list as $key => $m): ?>
        <div class="swiper-slide item">
            <section class="question-box" data-id="<?=$m['id']?>">
                <div class="q-title"><?=$m['question']?>
                </div>
                <?php if ($m['answerList']) {?>
                    <?php foreach ($m['answerList'] as $answer_key => $answer): ?>
                        <label class="radio-label">
                            <input type="radio" data-type="single_choice" name="<?=$m['id']?>" value="<?=$answer_key?>">
                            <?=$answer?>
                        </label>
                    <?php endforeach; ?>
                <?php }?>
            </section>
        </div>
    <?php endforeach; ?>
<?php }?>
  
 //例子2
  <select name="column_id" value="<?=isset($show_info['column_id']) ? $show_info['column_id'] : '0'?>">
    <?php foreach($column_tree as $key => $col) {?>
        <option value="<?=$key?>" <?=($show_info['column_id'] == $key) ? 'selected="selected"' : ''?>><?=$col?></option>
    <?php }?>
   </select>

Twig一些常用到的语法

//倒序排列
{{ loop.revindex }}
//

4、为了更好的兼容,点击事件写在a标签上。

5、微信网页开发

//微信网页开发分享监听
<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
<script type="text/javascript" src="https://res2.wx.qq.com/open/js/jweixin-1.6.0.js"></script>

<script>
var param =<?= $param ?>;
    (function () {
        wx.config({
            appId: '<?= $appid ?>',
            timestamp: param.timestamp,
            nonceStr: param.noncestr,
            signature: param.signature,
            jsApiList: [
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareWeibo',
                'onMenuShareQZone'
            ]
        });
        var shareContent = {
                "title": "title文案",
                "link": "<?= site_url('knowledge/index?share_id='.$share_id);?>",
                "imgUrl": "<?= site_url('/static/img/ai.png');?>",
                "desc": "文案~~~"
            },
            $jShareWrap = $('.js_share-wrap'),
            $slActiveWrap = $('.sl-active_toast-wrap'),
            $questionPage = $('#question_page'),
            $inviteMask = $('.invite-mask'),
            succFnActive = function () {        
                $.ajax({
                    url: '/knowledge/share_ins_count',
                    type: 'get',
                    success: function (r) {
                        r=JSON.parse(r);
                        console.log(r.ret);
                        $jShareWrap.removeClass('show'); 
                        $slActiveWrap.text(r.msg).show();
                        if(r.ret == 0){
                            $('.result-page .again-replay').removeClass('js_share_get_count');  
                            var hreflink=$('.result-page .again-replay').attr('data-type');  
                            console.log(hreflink);                    
                            $('.result-page .again-replay').attr('href',hreflink);
                         }
                        setTimeout(function(){
                            $slActiveWrap.text('').hide();
                            // if(r.ret == 0){
                            //     window.location.reload();
                            // }
                        },2000);                      
                    },
                    error: function () {
                    }
                });
            };
        wx.ready(function () {
            wx.onMenuShareTimeline({
                title: shareContent.title,
                link: shareContent.link,
                imgUrl: shareContent.imgUrl,
                desc: shareContent.desc,              
                success: function (res) {
                    console.log('pyq');
                    succFnActive();
                },
                cancel: function (res) {
                  
                }
            });

            wx.onMenuShareAppMessage({
                title: shareContent.title,
                link: shareContent.link,
                imgUrl: shareContent.imgUrl,
                desc: shareContent.desc,
                success: function () {
                    console.log('py');
                    succFnActive();
                }
            });
            wx.onMenuShareQQ({
                title: shareContent.title,
                link: shareContent.link,
                imgUrl: shareContent.imgUrl,
                desc: shareContent.desc,
                success: function () {
                    // succFn();
                }
            });
            wx.onMenuShareQZone({
                title: shareContent.title,
                link: shareContent.link,
                imgUrl: shareContent.imgUrl,
                desc: shareContent.desc,
                success: function () {
                    // succFn();
                }
            });
        });
    })();
</script>


//遇见坑
1、如果生成的签名param中的url与当前链接不一致控制台会报错。
2、shareContent中的图片等保持同域名

6、时间戳的对比

<!-- 当前时间戳 -->
<input type="hidden" name="nowtime" value="<?php echo  time() ?>" >
  
 //js 当前时间大于活动结束时间
  if (Number($('input[name="nowtime"]').val()) >= Math.round(new Date('2026-03-19T00:15:14+00:00').getTime()/1000)) {
    $('.timeEndBox').text('活动已结束,感谢。').show();
    return false;
  };

7、合成海报 html2canvas.min.js

html2canvas可以通过纯JS对浏览器端进行截屏,但截图的精确度还有待提高,部分css不可识别,所以在canvas中不能完美呈现原画面样式


//实例
function convertToPoster() {
    var $posterPageContent = $('#poster_page_content');
  ///这个地方只需要将useCORS设置成true,千万不要加allowTaint:true这两个不要同时加
    html2canvas($posterPageContent[0], {useCORS: true})
        .then(
            function (canvas) {
                var oImage = new Image();
// HTMLCanvasElement.toDataURL() 
//语法:canvas.toDataURL(type, encoderOptions);
// type为图片格式,默认为 image/png;encoderOptions为图片质量,默认为0.92
                oImage.src = canvas.toDataURL('image/png', 1);
                $(oImage)
                    .addClass('poster');
                $posterPageContent
                    .after(oImage)
                    .hide();
            }
        );
};

为了更清晰的前端合并图片

<img class="copyImage" src="">
<a id="dl-hidden" style="display:none;"></a>
window.onload = function(){
    var IMAGE_URL;
    function takeScreenshot(){
        var shareContent = document.getElementById('letter');//需要截图的包裹的(原生的)DOM 对象
        var width = shareContent.offsetWidth; //获取dom 宽度
        var height = shareContent.offsetHeight; //获取dom 高度
        var canvas = document.createElement("canvas"); //创建一个canvas节点

        var scale = 3; //定义任意放大倍数 支持小数
        canvas.width = width * scale; //定义canvas 宽度 * 缩放
        canvas.height = height * scale; //定义canvas高度 *缩放
        canvas.getContext("2d").scale(scale,scale); //获取context,设置scale

        // var rect = shareContent.getBoundingClientRect();//获取元素相对于视察的偏移量
        // canvas.getContext("2d").translate(-rect.left,-rect.top);//设置context位置,值为相对于视窗的偏移量负值,让图片复位
        var opts = {
            scale:scale, // 添加的scale 参数
            canvas:canvas, //自定义 canvas
            logging: true, //日志开关
            width:width, //dom 原始宽度
            height:height, //dom 原始高度
            backgroundColor: 'transparent',
        };
        html2canvas(shareContent, opts).then(function (canvas) {
            IMAGE_URL = canvas.toDataURL("image/png");
            $('.copyImage').attr('src',IMAGE_URL);
        })
    }

    function dataURLtoBlob(dataurl) {
        var arr = dataurl.split(','),
            mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]),
            n = bstr.length,
            u8arr = new Uint8Array(n)
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
        }
        return new Blob([u8arr], { type: mime })
    }

    function downloadBase64(dataUrl, filename) {
        var imageFile, href
        // const downloadLink = document.createElement('a')
        var downloadLink = document.getElementById('dl-hidden')
        try {
            var blob = dataURLtoBlob(dataUrl)
                var href = window.URL.createObjectURL(blob)
                downloadLink.download = filename
                downloadLink.href = href
                downloadLink.click()
        } catch (err) {
        } finally {
            if (href) {
                window.URL.revokeObjectURL(href)
            }
            // downloadLink.remove()
        }
    }
           // $(".letter-title").text('木子芳小芳');
            takeScreenshot();
            $("#save-local").click(function(e){
             downloadBase64(IMAGE_URL, 'zhengshu.png')
            })
}

8、计时器

  // 计时器
    var time_share=0;
    var timeStart = function () {
        var hour = 0;
        var min = 0;
        var sen = 0;

        function showTime() {
             time_share ++;
            sen++;
            if (sen >= 60) {
                min++;
                sen = 0;
            }
            if (min >= 60) {
                hour++;
                min = 0;
            }
            if (hour >= 12) {
                hour = 0;
            }
            var dataStr = "<span class='timespan'>" + (hour < 10 ? ("0" + hour) : hour) + "</span>:<span class='timespan'>" + (min < 10 ? ("0" + min) : min) + "</span>:<span class='timespan'>" + (sen < 10 ? ("0" + sen) : sen) + "</span>";
            $(".vtimeShow").html(dataStr);
        }
        setInterval(showTime, 1000);
       
    };

答题滑动轮播坑

-->答题滑动的时候,执行相关内容可以放在一个一个方法里,寻找合适时机触发
 //  答题页面的轮播交互
    var knowledgeSwiper;
    function handleStartDo() {
        knowledgeSwiper = new Swiper('.js_knowledge-swiper', {
            on: {
                //题目滑动
                slideChange: function () {
                    //slider的状态判断
                    if (knowledgeSwiper.isBeginning) {
                        $preSlider.addClass('disabled');
                    } else if (knowledgeSwiper.isEnd) {
                        $nextSlider.hide();
                        $submitPaper.show();
                    } else {
                        $preSlider.removeClass('disabled');
                        $submitPaper.hide();
                        $nextSlider.show();
                    };
                    $('#activeIndex').text(this.activeIndex + 1);
                }
            }
        });
        $('.js_pre-slider').off('click').on('click', function () {
            knowledgeSwiper.slidePrev();
        });
        $('.js_next-slider').off('click').on('click', function () {
            knowledgeSwiper.slideNext();
        });
    }; // 做题交互end

数据异步追加

//第一步--每条数据渲染的格式
function listHtmlRender(data, orderNum) {
        var htmlArr = [
            '<li>',
                '<span class="order">',
                    orderNum,
                '</span>',
                '<img src="' + data.headimgurl + '" class="avatar">',
                '<span class="nickname">',
                    data.nickname,
                '</span>',
                '<span class="time">'
                + '用时' + data.time_share + 's' +
                '</span>',
            '</li>'
        ];
        var htmlStr = htmlArr.join('');
        return htmlStr;
    };
//第二部ajax请求后的
for (var i = 0; i < r.date.length; i++) {
  orderNum++;
  var listHtml = listHtmlRender(response.data[i], orderNum);
  $listBoxUl.append($(listHtml));
}

iframe适配

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>工业大数据</title>
    <style>
        html,
        body {
            width: 100%;
            height: 100%;
            overflow: hidden;
        }

        .iframe_wrap {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            bottom: 0;
            z-index: 11;
            overflow-y: hidden;
            -webkit-overflow-scrolling: touch;
            box-sizing: border-box;
        }

        .iframe_wrap iframe {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            width: 100%;
            height: 100%;
            //min-height
            /* min-height:366px; */
            overflow: hidden;
            background: transparent;
        }
    </style>
</head>

<body>
    <div class="iframe_wrap">
        <iframe src="网址" frameborder="0"></iframe>
    </div>
</body>
</html>