美文网首页
原生JS监听窗口缩放

原生JS监听窗口缩放

作者: 你这个锤子 | 来源:发表于2020-06-20 13:58 被阅读0次

    目录

    • 把图片 Mask1 替换成 Mask2
    • 更改标签样式

    实例:当窗口小于450的时候把图片Mask1替换成Mask2

    window.onresize = function () {  
      console.log('监听变化')
      watchChangeSize();
    };
    function watchChangeSize (){
      //可视区的宽/高(DOM)
      //offsetHeight(带边框)和clientHeight(不带边框)     
      var offsetWid = document.documentElement.clientWidth;
      var offsetHei = document.documentElement.clientHeight;
      if (offsetWid < 450) {
        var follow = document.getElementsByClassName("footer_weijin_img")[0];
        var follow_src_path = follow.src;
        console.log(new_era_src_path)
        var follow_src_name = follow_src_path.split("/");
        if(follow_src_name[follow_src_name.length-1] == "Mask1.jpg"){
          var _src = '';
          for (var i=0;i<follow_src_name.length;i++) {
            if (i < (follow_src_name.length - 1)) {
              _src = _src + follow_src_name[i] + '/'
            } else {
              _src = _src + 'Mask2.png'
            }
          }
          follow.src = _src;
        }
      }
    

    实例:更改标签样式

    function watchChangeSize (){
        //可视区的宽/高(DOM)
        //offsetHeight(带边框)和clientHeight(不带边框)区别参考上一篇文章     
        var offsetWid = document.documentElement.clientWidth;
        var offsetHei = document.documentElement.clientHeight;
        if (offsetWid < 450) {
            var follow = document.getElementsByClassName("footer_weijin_p")[0].style;
            follow.display = 'none'
            var follow_img = document.getElementsByClassName("footer_weijin_img")[0].style;
            follow_img.display = 'flex'
        } else {
            var follow = document.getElementsByClassName("footer_weijin_p")[0].style;
            follow.display = 'block'
            var follow_img = document.getElementsByClassName("footer_weijin_img")[0].style;
            follow_img.display = 'none'
        }
    }
    

    窗口缩放用到的

    单位 rem 
    veb给的:
    !function(){var e=document.documentElement;a=function(){var n=e.getBoundingClientRect().width;n<1200&&(n=1200),e.style.fontSize=100/1920*(n>=1920?1920:n)+"px"},c=null,window.addEventListener("resize",function(){clearTimeout(c),c=setTimeout(a,10)}),a()}()
    
    
    //京东凹凸实验室的
    // taro
    <script>
        !function(x){function w(){var v,u,t,tes,s=x.document,r=s.documentElement,a=r.getBoundingClientRect().width;if(!v&&!u){var n=!!x.navigator.appVersion.match(/AppleWebKit.*Mobile.*/);v=x.devicePixelRatio;tes=x.devicePixelRatio;v=n?v:1,u=1/v}if(a>=640){r.style.fontSize="40px"}else{if(a<=320){r.style.fontSize="20px"}else{r.style.fontSize=a/320*20+"px"}}}x.addEventListener("resize",function(){w()});w()}(window);
      </script>
        
    

    相关文章

      网友评论

          本文标题:原生JS监听窗口缩放

          本文链接:https://www.haomeiwen.com/subject/cxgwxktx.html