Java自学者论坛

 找回密码
 立即注册

手机号码,快捷登录

恭喜Java自学者论坛(https://www.javazxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,会员资料板块,购买链接:点击进入购买VIP会员

JAVA高级面试进阶训练营视频教程

Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程Go语言视频零基础入门到精通Java架构师3期(课件+源码)
Java开发全终端实战租房项目视频教程SpringBoot2.X入门到高级使用教程大数据培训第六期全套视频教程深度学习(CNN RNN GAN)算法原理Java亿级流量电商系统视频教程
互联网架构师视频教程年薪50万Spark2.0从入门到精通年薪50万!人工智能学习路线教程年薪50万大数据入门到精通学习路线年薪50万机器学习入门到精通教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程MySQL入门到精通教程
查看: 543|回复: 0

[jQuery]无法获取隐藏元素(display:none)宽度(width)和高度(height)的新解决方案

[复制链接]
  • TA的每日心情
    奋斗
    昨天 16:00
  • 签到天数: 755 天

    [LV.10]以坛为家III

    2034

    主题

    2092

    帖子

    70万

    积分

    管理员

    Rank: 9Rank: 9Rank: 9

    积分
    707348
    发表于 2021-4-20 13:26:39 | 显示全部楼层 |阅读模式

    在做茶城网改版工作的时候,又遇到一个新问题,我需要用jQuery写一个通过点击左右图标来翻阅图片的小插件,写好后测试可以正常运行,但是放到Tab中后发现只有第一个Tab中的代码能够正常运行,其它全部罢工了。

     
      用Chrome自带的开发工具一查,发现罢工的Tab中。小插件一些重要元素的宽度都变成“0”了,因为这个小插件需要计算动态宽度来实现,于是马上想到是小插件中的宽度获取失败了,果不其然。
     
      汗,居然一直没发现jQuery无法获取隐藏元素 (display:none)的宽度 (width)和高度 (height),为了兼容IE6,我用1.x版,而且是官方最新的1.10.2版,不知道在2.x版中这个问题有没有解决。
     
      既然jQuery都不支持,那么Javascript也就肯定不支持了,网上搜索了一下,有个解决方案是用 visibility:hidden来代替 display:none,由于 visibility:hidden占用物理空间,因此可以获取宽高。
     
      问题是这需要我去改动已经写好的Tab插件,这种拆东墙补西墙的事情,总会让人感觉不爽的。长时间搜索其它解决方案无果,就在我快要妥协的时候,突然眼前一亮,发现了个好东西: jQuery Actual
     
      可以说它几乎完美的解决了这个问题,而且使用方法极其简单,使用 $('#someElement').actual('width')的方式来代替 $('#someElement').width()就可以了,兼容性也十分出色,可以兼容IE6浏览器,压缩后体积只有1.1K也是一大亮点,更牛的是还支持inner和outer的计算。

     

    官方信息
     
    jQuery版本要求
    • jQuery 1.2.3+
     
    所兼容的浏览器
    • Firefox 2.0+
    • Internet Explorer 6+
    • Safari 3+
    • Opera 10.6+
    • Chrome 8+
    安装方法
    • HTML文档需要声明DOCTYPE
    • 引用JS文件即可
      <script type="text/javascript" src="path/jquery.min.js"></script>
      <script type="text/javascript" src="path/jquery.actual.js"></script>
    使用方法
    • 代码范例
    • //get hidden element actual width
      $('.hidden').actual('width');
      
      //get hidden element actual innerWidth
      $('.hidden').actual('innerWidth');
      
      //get hidden element actual outerWidth
      $('.hidden').actual('outerWidth');
      
      //get hidden element actual outerWidth and set the `includeMargin` argument
      $('.hidden').actual('outerWidth',{includeMargin:true});
      
      //get hidden element actual height
      $('.hidden').actual('height');
      
      //get hidden element actual innerHeight
      $('.hidden').actual('innerHeight');
      
      //get hidden element actual outerHeight
      $('.hidden').actual('outerHeight');
      
      // get hidden element actual outerHeight and set the `includeMargin` argument
      $('.hidden').actual('outerHeight',{includeMargin:true});
      
      //if the page jumps or blinks, pass a attribute '{ absolute : true }'
      //be very careful, you might get a wrong result depends on how you makrup your html and css
      $('.hidden').actual('height',{absolute:true});
      
      // if you use css3pie with a float element
      // for example a rounded corner navigation menu you can also try to pass a attribute '{ clone : true }'
      // please see demo/css3pie in action
      $('.hidden').actual('width',{clone:true});

      个人觉得jQuery官方应该考虑将这个功能写进内核,那就更方便了。为了防止以后jQuery Actual的官网打不开(现在就时不时会和谐)或者下载不了,在这里存一份jquery.actual.js的源码,以备不时只需。

    • 源码:jquery.actual.js

      ;( function ( $ ){
       $.fn.addBack = $.fn.addBack || $.fn.andSelf;
      
       $.fn.extend({
      
         actual : function ( method, options ){
           // check if the jQuery method exist
           if( !this[ method ]){
             throw '$.actual => The jQuery method "' + method + '" you called does not exist';
           }
      
           var defaults = {
             absolute      : false,
             clone         : false,
             includeMargin : false
           };
      
           var configs = $.extend( defaults, options );
      
           var $target = this.eq( 0 );
           var fix, restore;
      
           if( configs.clone === true ){
             fix = function (){
               var style = 'position: absolute !important; top: -1000 !important; ';
      
               // this is useful with css3pie
               $target = $target.
                 clone().
                 attr( 'style', style ).
                 appendTo( 'body' );
             };
      
             restore = function (){
               // remove DOM element after getting the width
               $target.remove();
             };
           }else{
             var tmp   = [];
             var style = '';
             var $hidden;
      
             fix = function (){
               // get all hidden parents
               $hidden = $target.parents().addBack().filter( ':hidden' );
               style   += 'visibility: hidden !important; display: block !important; ';
      
               if( configs.absolute === true ) style += 'position: absolute !important; ';
      
               // save the origin style props
               // set the hidden el css to be got the actual value later
               $hidden.each( function (){
                 var $this = $( this );
      
                 // Save original style. If no style was set, attr() returns undefined
                 tmp.push( $this.attr( 'style' ));
                 $this.attr( 'style', style );
               });
             };
      
             restore = function (){
               // restore origin style values
               $hidden.each( function ( i ){
                 var $this = $( this );
                 var _tmp  = tmp[ i ];
      
                 if( _tmp === undefined ){
                   $this.removeAttr( 'style' );
                 }else{
                   $this.attr( 'style', _tmp );
                 }
               });
             };
           }
      
           fix();
           // get the actual value with user specific methed
           // it can be 'width', 'height', 'outerWidth', 'innerWidth'... etc
           // configs.includeMargin only works for 'outerWidth' and 'outerHeight'
           var actual = /(outer)/.test( method ) ?
             $target[ method ]( configs.includeMargin ) :
             $target[ method ]();
      
           restore();
           // IMPORTANT, this plugin only return the value of the first element
           return actual;
         }
       });
      })( jQuery );

       此上是转载别人的文章。

    • 此外我还发现,如果觉得上述方法未曾听过或者不知道,但是要知道原因,为什么会取不到高度,这是今天一直困扰我的问题。因为我在获取高度之前,对前面的元素添加了隐藏的动作,我用的是hide(),但是在页面的标签上就会形成display:none;这个动作,所以之后我再取值就得不到了。读了上述之后,瞬间明白。jQuery无法获取隐藏元素(display:none)的宽度(width)和高度(height),解决方案是用visibility:hidden来代替display:none,由于visibility:hidden占用物理空间,因此可以获取宽高。
    哎...今天够累的,签到来了1...
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|小黑屋|Java自学者论坛 ( 声明:本站文章及资料整理自互联网,用于Java自学者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-6-27 17:46 , Processed in 0.068407 second(s), 27 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表