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
JS无法获取display为none的隐藏元素的宽度和高度的解决方案的更多相关文章
- JS获取display为none的隐藏元素的宽度和高度的解决方案
有时候,我们一进入页面,就需要获取display为none元素的物理尺寸(宽高),或获取display为none元素的子元素的物理尺寸(宽高),本篇文章就如何解决以上问题给出自己的解决方案 <h ...
- jQuery获取display为none的隐藏元素的宽度和高度的解决方案
1.利用给元素添加行内样式:visibility:hidden;display:block 2.让隐藏元素变成有物理尺寸存在,但不可见,获取元素宽高 3.再给它还原成display为none,去除vi ...
- Js中获取显示器、浏览器以及窗口等的宽度与高度的方法
网页可见区域宽:document.body.clientWidth 网页可见区域高:document.body.clientHeight 网页可见区域宽:document.body.offsetWid ...
- jQuery获取或设置元素的宽度和高度
jQuery获取或设置元素的宽度和高度: 可使用以下3种方法: 1,jQuery width() 和 height() 方法: 2,innerWidth() 和 innerHeight() 方法: 3 ...
- 使用jQuery获取元素的宽度或高度的几种情况
今天说说使用jQuery获取元素大小的遇到几种情况 使用jQuery获取元素的宽度或高度的有几种情况: 1.使用width(),它只能获取当前元素的内容的宽度: 2.使用innerWidth(),它只 ...
- 获取display:none的元素的宽度和高度
display为none的元素不能通过offsetWidth和offsetHeight来获取宽高(未参与css渲染), 解决方案:可以通过在display为none的元素使用行内样式style设置宽高 ...
- js 冒泡事件 点击任意地方隐藏元素
$(function () { $("#but").click(function (e) {// $();//显示速度 /*阻止冒泡事件*/ e = window.event || ...
- js正则获取html字符串指定的dom元素和内容
var str = "<div>111<p id='abc'>3333</p></div><div>222<div id=' ...
- js滚动到指定位置显示或隐藏元素
$(function(){ $(window).scroll(function(){ var scroll_top=$(window).scrollTop(); console.log(scroll_ ...
随机推荐
- Key-Value 数据库简介
1.Aerospike 官方网站:https://www.aerospike.com/ Aerospike是一个以分布式为核心基础,可基于行随机存取内存中索引.数据或SSD存储中数据的数据库. Aer ...
- Aseprite入门:第一个gif动图
前言:Aseprite入门教程 1.新建图片: 选择新建文件,然后选定宽高和颜色及背景类型,点击OK进行图片的创建: 2.绘制一个基础图形,为了方便还是选用球形: 填充上颜色: 美化(添加阴影增加小球 ...
- IdentityServer4源码颁发token分析及性能优化
IdentityServer4源码地址 IdentityModel源码地址 以下的流程用ResourceOwnerPassword类型获取token作为介绍 分两种获取形式说明 token请求地址为默 ...
- ES6的Promise
推荐一下我觉得不错关于Promise的好文章,通俗易懂 说起ES6的Promise就要提及一下JQ的$.when()方法,两者基本相同 面试的时候经常会问Promise,如果同学们能在回答Promis ...
- sql server 索引阐述系列五 索引参数与碎片
-- 创建聚集索引 create table [dbo].[pub_stocktest] add constraint [pk_pub_stocktest] primary key clustered ...
- wamp解决ajax跨域问题
若使用ajax测试本地数据时,遇到的跨域问题,如 因为ajax只能用于请求服务器的数据,而在本地测试,打开的文件是以 file:// 的形式, 所以报错 可以通过 nginx 建立反向代理,处理静态文 ...
- ES6 系列之私有变量的实现
前言 在阅读 <ECMAScript 6 入门>的时候,零散的看到有私有变量的实现,所以在此总结一篇. 1. 约定 实现 class Example { constructor() { t ...
- Hadoop YARN架构设计要点
YARN是开源项目Hadoop的一个资源管理系统,最初设计是为了解决Hadoop中MapReduce计算框架中的资源管理问题,但是现在它已经是一个更加通用的资源管理系统,可以把MapReduce计算框 ...
- 在Windows Server 2008 R2上安装IIS服务
一.Windows Server 2008 R2 介绍 1.Windows Server 2008 R2 基本概念 2.Windows Server 2008 R2 家族系列 二.VMware虚拟机安 ...
- Web前端课程设计——个人主页
大三上学期期末总结,嗯,没错,是上学期,写在新学期开始hhh. 上学期学了一门HTML5+CSS3的课程,也叫Web前端技术,期末的课程设计是写一个个人主页,能够在浏览器中打开的静态网页.通过一学期的 ...