JS无法获取display为none的隐藏元素的宽度和高度的解决方案

在实际开发中会遇到确实需要获取隐藏元素的宽高,这儿所说的隐藏元素是display为none的元素。

可使用jQuery Actual Plugin插件来完成,其源码如下:

;( 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,
display       : 'block'
};
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: '   configs.display   ' !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 (){
// Save original style. If no style was set, attr() returns undefined
var $this     = $( this );
var thisStyle = $this.attr( 'style' );
tmp.push( thisStyle );
// Retain as much of the original style as possible, if there is one
$this.attr( 'style', thisStyle ? thisStyle   ';'   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);

当然如果要支持模块化开发,直接使用官网下载的文件即可,源码也贴上:

;( function ( factory ) {
if ( typeof define === 'function' && define.amd ) {
// AMD. Register module depending on jQuery using requirejs define.
define( ['jquery'], factory );
} else {
// No AMD.
    factory( jQuery );
}
}( 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,
display       : 'block'
};
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: '   configs.display   ' !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 (){
// Save original style. If no style was set, attr() returns undefined
var $this     = $( this );
var thisStyle = $this.attr( 'style' );
tmp.push( thisStyle );
// Retain as much of the original style as possible, if there is one
$this.attr( 'style', thisStyle ? thisStyle   ';'   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;
}
});
}));

代码实例:

//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});

插件地址:http://dreamerslab.com/works


更多专业前端知识,请上 【猿2048】www.mk2048.com

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/366075.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

删除kafka topic

1、因为项目原因,kakfa通道中经常造成数据阻塞,导致kafka通道中数据量过大,因此我需要将kakfa通道中数据清除(个人项目原因,一直使用一个消费者,只要保证当前消费者不在消费之前很久的数据就可以。因数量过…

启动oracle数据库工具,Oracle数据库常用工具

SQL*Plus:SQL*Plus 是Oracle 数据库的一个基本工具,它允许用户使用SQL 命令交互式的访问数据库,也允许用户使用SQL*Plus 命令格式化输出参数。 通过SQL*Plus ,可以完成数据库的启动和停止、创建和运行查询、更新数据、格式化输出数据报表、运…

可持久化并查集小结

https://www.zybuluo.com/ysner/note/1253722 定义 允许恢复历史状态的并查集。 建立 建\(Q\)棵主席树,每个主席树上维护当前状态并查集各个节点的父亲。 (实际上就是并查集和主席树强行捆绑在一起) 操作 每次操作前自动继承上次操作后的状态…

Java 获取linux根目录下的文件夹_Windows支持直接访问Linux子系统文件:你的下一台Linux何必是Linux...

2020年第一波薅当当网羊毛的机会,别错过!晓查 发自 凹非寺 量子位 报道 | 公众号 QbitAI 微软,致力于做最好的Linux发行版。今天,安装Windows 10测试版本号19603的用户发现,系统里WSL (Windows中的Linux子系统…

HTML5效果:实现树叶飘落

实现如图所示的东西效果&#xff08;落叶下落&#xff09;&#xff1a; html代码&#xff1a; <!DOCTYPE html><html><head><title>HTML5树叶飘落动画</title><meta charset"utf-8"><meta name"viewport" content&…

Java 8 Friday Goodies:Lambda和XML

在Data Geekery &#xff0c;我们喜欢Java。 而且&#xff0c;由于我们真的很喜欢jOOQ的流畅的API和查询DSL &#xff0c;我们对Java 8将为我们的生态系统带来什么感到非常兴奋。 我们已经写了一些关于Java 8好东西的博客 &#xff0c;现在我们觉得是时候开始一个新的博客系列了…

洛谷2619/bzoj2654 Tree(凸优化+MST)

bzoj的数据是真的水。。 qwq 由于本人还有很多东西不是很理解 qwq 所以这里只写一个正确的做法。 首先&#xff0c;我们会发现&#xff0c;对于你选择白色边的数目&#xff0c;随着数目的上涨&#xff0c;斜率是单调升高的。 那么这时候我们就可以考虑凸优化&#xff0c;也就是…

oracle 创交表,创建交叉报表(oracle)_oracle

创建交叉报表create table t1(goodid number(10) not null,saledate date not null,salesum number(10));要求生成本年度每个月的产品销售状况表m1 m2 m3 ... m12g1g2...gn下面是生成报表的sqlSELECT goodid,SUM(decode(to_char(saledate,mm),01,salesum)) "01"…

cass方格网数据excel_讨论|CASS怎么计算回字型土方? 124

大家好,欢迎来到我的专栏。这是我原创的第124篇CASS应用技术干货文章。希望对你有所帮助&#xff0c;写文不易&#xff0c;请点赞哦!回字型土方工程&#xff0c;就是计算区域内部&#xff0c;有一个或多个不参加计算的区域&#xff0c;这种区域也就是常说的“扣岛”。常见的有基…

ATM购物车程序项目规范(更新到高级版)

ATM购物车程序&#xff08;高级版&#xff09; 之前的低级版本已经删除&#xff0c;现在的内容太多&#xff0c;没时间把内容上传&#xff0c;有时间我会把项目源码奉上&#xff01; 我已经把整个项目源码传到群文件里了&#xff0c;需要的可以加主页qq群号。同时群内也有免费的…

垃圾收集器准则和提示

这些是我需要调整GC时通常会看到的一些准则和技巧。 主要由以下两本书组成&#xff0c;而根据我的经验却很少&#xff1a; Java性能 JBoss AS 5性能调优 希望它们对那里的其他人有用&#xff01; 垃圾收集器 XX:AggressiveOpts将HotSpot内部布尔变量设置为true以启用其他性…

MD5加密处理

MD5 加密后的位数一般为两种&#xff0c;16 位与 32 位。16 位实际上是从 32 位字符串中&#xff0c;取中间的第 9 位到第 24 位的部分 using System; using System.Security.Cryptography; using System.Text;namespace _04MD5加密 {internal class Program{private static vo…

php tp 支付宝 支付,php实现的支付宝网页支付功能示例【基于TP5框架】

本文实例讲述了php实现的支付宝网页支付功能。分享给大家供大家参考&#xff0c;具体如下&#xff1a;1.提交支付请求require_once ./payment/zfb/pagepay/service/AlipayTradeService.php;require_once ./payment/zfb/pagepay/buildermodel/AlipayTradePagePayContentBuilder.…

移动前端—H5实现图片先压缩再上传

在做移动端图片上传的时候&#xff0c;用户传的都是手机本地图片&#xff0c;而本地图片一般都相对比较大&#xff0c;拿iphone6来说&#xff0c;平时拍很多图片都是一两M的&#xff0c;如果直接这样上传&#xff0c;那图片就太大了&#xff0c;如果用户用的是移动流量&#xf…

requests模块

python requests用法总结 本文全部来源于官方文档 http://docs.python-requests.org/en/master/ 1、安装 Requests 是一个第三方 Python 模块&#xff0c;其官网的介绍如下&#xff1a; Requests 唯一的一个非转基因的 Python HTTP 库&#xff0c;人类可以安全享用。 警告&…

假期周总结六

放假第六周所做事情为&#xff1a; 1、在网上找了相关教程学习安装Hadoop,但过程中出现了许多问题&#xff0c;中途放弃了 2、继续观看关于大数据的在线课程视频转载于:https://www.cnblogs.com/DaisyYuanyq/p/9583194.html

linux子系统备份,使用LxRunOffline工具备份/还原Linux子系统(WSL)

安装WSL开启WSL组件首先需要打开WSL组件&#xff0c;可以使用以下命令&#xff1a;Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux也可以手动在【控制面板】-【程序】-【启用或关闭Windows功能】-【适用于Linux的Windows子系统】打勾&…

react打包后图片丢失_手搭一个 React,Typescript,Koa,GraphQL 环境

本文系原创&#xff0c;转载请附带作者信息&#xff1a;yhlben项目地址&#xff1a;https://github.com/yhlben/cdfang-spider前言在实际的开发过程中&#xff0c;从零开始初始化一个项目往往很麻烦&#xff0c;所以各种各样的脚手架工具应运而生。crea-react-app&#xff0c;v…

无需改动现有网络,企业高速远程访问内网Linux服务器

某企业为数据治理工具盒厂商&#xff0c;帮助客户摆脱数据问题困扰、轻松使用数据&#xff0c;使得客户可以把更多精力投入至数据应用及业务赋能&#xff0c;让数据充分发挥其作为生产要素的作用。 目前&#xff0c;该企业在北京、南京、西安、武汉等地均设有产研中心&#xff…

AngularJS XMLHttpRequest

$http 是 AngularJS 中的一个核心服务&#xff0c;用于读取远程服务器的数据。 读取 JSON 文件 下是存储在web服务器上的 JSON 文件&#xff1a; {"records": [{"Name": "Alfreds Futterkiste","City": "Berlin","Co…