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_ ...
随机推荐
- iframe简单框架
<iframe width='738' height='523' class='preview-iframe' scrolling='no' frameborder='0' src='http: ...
- 使用本地缓存快还是使用redis缓存好?
使用本地缓存快还是使用redis缓存好? Redis早已家喻户晓,其性能自不必多说. 但是总有些时候,我们想把性能再提升一点,想着redis是个远程服务,性能也许不够,于是想用本地缓存试试!想法是不错 ...
- MySql事务的隔离级别及作用
逻辑工作单元遵循一系列(ACID)规则则称为事务. 原子性:保证事务是一系列的运作,如果中间过程有一个不成功则全部回滚,全部成功则成功.保证了事务的原则性. 一致性:一致性指的是比如A向B转100块钱 ...
- Apache XBean相关说明,待补充
前言 最近在看ActiveMQ5.15.0源码,发现ActiveMQ实际上是基于spring实现的,其配置文件activemq.xml中有个broker元素节点,使用的就是Apache XBean的配 ...
- [机器学习]回归--Decision Tree Regression
CART决策树又称分类回归树,当数据集的因变量为连续性数值时,该树算法就是一个回归树,可以用叶节点观察的均值作为预测值:当数据集的因变量为离散型数值时,该树算法就是一个分类树,可以很好的解决分类问题. ...
- [转]phpredis中文手册
本文是参考<redis中文手册>,将示例代码用php来实现,注意php-redis与redis_cli的区别(主要是返回值类型和参数用法). 目录(使用CTRL+F快速查找命令): Key ...
- shell脚本--cut命令
bash&shell系列文章:http://www.cnblogs.com/f-ck-need-u/p/7048359.html 1.1 选项说明 cut命令将行按指定的分隔符分割成多列,它的 ...
- Perl输出复杂数据结构:Data::Dumper,Data::Dump,Data::Printer
输出复杂结构 Data::Dumper.Data::Dump.Data::Printer都可以用来输出复杂的数据结构.本文只介绍简单的几个输出形式,以后再需要的地方再详细介绍. 前两者建议传递数据结构 ...
- 聊聊数据库~2.SQL环境篇
传统数据库 上篇文章:聊聊数据库~开篇 https://www.cnblogs.com/dotnetcrazy/p/9690466.html 本来准备直接开讲NoSQL的(当时开篇就是说的NoSQL) ...
- SqlServer 技术点总结(持续更新)
本文是用于记录自己平时遇到的一些SQL问题或知识点,以便以后自己查阅,会持续的更新,增加内容.发在博客园也可以和各位博友共同学习交流,如文中记录的有错误之处希望指出,谢谢. 一.用SQL语句调用作业 ...