返回CSS高度与Jquery,不计算,但声明 [英] Return CSS Height with Jquery, Not computed, but declared

查看:102
本文介绍了返回CSS高度与Jquery,不计算,但声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这可能是以前版本的jquery的默认,但是当我调用 .css(height)。 height(),它返回计算的高度,这不是我想要的 - 我只想要一个高度值,如果它是一个CSS文件中明确声明的元素。



就像没有在任何地方声明一样,也许可以返回'auto' / p>

例如,我的CSS看起来像这样:

  .element { 
margin-left:5px;
color:red;
}

.css(margin-left)返回5px,而 .css(height)返回 20

$

$

解决方案

浏览器自动计算CSS高度和宽度。



例如,您可以在Chrome开发人员工具(F12)中的计算样式标签中查看它们



和文档:



jQuery.width()


获取
匹配元素集合中第一个元素的当前计算宽度或设置每个匹配元素的宽度元素。



.css(width)和.width()之间的区别是后者
返回一个无单位像素值),而前者
返回一个单位完整的值(例如,400像素)


但是如果你想得到正确CSS值,我可以建议不要使用jQuery



如果我们有HTML:

 code>< div id =elemstyle =height:auto>< / div> 

我们可以写JS:

  $('#elem')。get(0).style.height //auto

$ b b

如果我们有HTML:

 < div id =elem> div> 

JS:

  $('#elem')。get(0).style.height //


$ b b

通用函数

  var height = function(elem){
return $(elem).get(0).style.height ===? $(elem).height():$(elem).get(0).style.height;
}


I think this might have been the default in a previous version of jquery, but when I call .css("height") and .height(), it returns the computed height, which isn't what I want- I only want a height value if it is specifically declared in a CSS file for that element.

Like if it isn't declared anywhere, perhaps it could return 'auto' like it does for top and left sometimes...

For example, my CSS looks like this:

.element{
    margin-left:5px;
    color:red;
}

.css("margin-left") returns "5px", while .css("height") returns 20 even though it isn't specifically set...

Thanks

解决方案

The browser automatically calculates CSS height and width.

You can see them, for example, in tab "Computed styles" in Chrome Developers Tools(F12)

And docs:

jQuery.width()

Get the current computed width for the first element in the set of matched elements or set the width of every matched element.

The difference between .css(width) and .width() is that the latter returns a unit-less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px)

But if you want to get correct CSS value, i can advise don't use jQuery

if we have HTML:

<div id="elem" style="height: auto"></div>

we can write JS:

$('#elem').get(0).style.height    // "auto"

if we have HTML:

<div id="elem"></div>

JS:

$('#elem').get(0).style.height    // ""

universal function:

var height = function(elem){
      return $(elem).get(0).style.height === "" ? $(elem).height() : $(elem).get(0).style.height;
}

这篇关于返回CSS高度与Jquery,不计算,但声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆