简体   繁体   English

如何在纯JavaScript中获取css属性值

[英]How to get css property value in pure javascript

I want to get the width of an element in percentage. 我想以百分比形式获得元素的宽度。 I am using the following function to get the style but it gives the value in pixels. 我使用以下函数来获取样式,但它以像素为单位给出值。 Here the variable style can be any css property like width, height etc. 这里变量样式可以是任何css属性,如宽度,高度等。

this.getStyle = function(style) {
    var elementStyle = window.getComputedStyle(that.element);
    var value = elementName.getPropertyValue(style);
    return value;
}

Seems that you're looking for 似乎你正在寻找

that.element.style.width
that.element.style.height
etc

I think you get always pixels, rather than % width. 我认为你总是得到像素,而不是%宽度。 The reason is while object render it always set physical width based on% we given, this you can verify via dom. 原因是在对象渲染时它始终根据我们给出的%设置物理宽度,这可以通过dom进行验证。 Javascript use DOM(Document Object Model) , while jQuery you can use Dom as well as before load property via document.getready() . Javascript使用DOM(Document Object Model) ,而jQuery可以使用Dom以及通过document.getready()加载属性之前。

So as above you can get the property, but in pixels. 因此,如上所述,您可以获得属性,但以像素为单位。

document.getElementById('yourdivname').element.style.width

or 要么

div2 = document.getElementById('div2');
alert("Width of div2 with style = " + div2.style.width);

Getting the width of an html element in percent % with jQuery 使用jQuery获取html元素的宽度百分比%

This is interesting : 这是有趣的 :

  1. Is it possible to use jQuery to get the width of an element in percent or pixels, based on what the developer specified with CSS? 根据开发人员用CSS指定的内容,是否可以使用jQuery以百分比或像素为单位获取元素的宽度?

  2. http://www.lucemorker.com/blog/javascript-vs-jquery-quick-overview-and-comparison http://www.lucemorker.com/blog/javascript-vs-jquery-quick-overview-and-comparison

$(document).ready is a jQuery event to be triggered after the HTML document has been loaded vs onload is a built-in DOM event to be triggered after all content has been loaded. $(document).ready是在加载HTML文档后要触发的jQuery事件,而onload是在加载所有内容后触发的内置DOM事件。 So the ready event would normally fire earlier than the onload event, allowing code execution as early as possible without having to wait for all assets to be fully loaded 因此,ready事件通常会比onload事件更早发生,允许尽可能早地执行代码,而不必等待所有资产完全加载

For more details :- click this link . 有关详细信息: - 单击此链接

你尝试过这样的事情:

var width = (100 * parseFloat($('.largeField').css('width')) / parseFloat($('.largeField').parent().css('width')) ) + '%';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM