Javascript jQuery获取属性不合时宜

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3552034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:08:47  来源:igfitidea点击:

jQuery get attribute out of style

javascriptjquerycss

提问by skerit

I need to extract something out of the "style" attribute: the "top" and "left" attribute

我需要从“style”属性中提取一些东西:“top”和“left”属性

<div style="top: 250px; left: 250px;" id="1" class="window ui-draggable">

What's the best way of doing this with jQuery? Is there an easy way, or will I have to resort to string functions?

使用 jQuery 执行此操作的最佳方法是什么?有没有简单的方法,还是我必须求助于字符串函数?

回答by Pekka

It depends what you need. If you need the computed value - e.g. the actual value the browser used after parsing all the style sheets - use

这取决于你需要什么。如果您需要计算值 - 例如浏览器在解析所有样式表后使用的实际值 - 使用

$("#element_1").css("top")
$("#element_1").css("left")

If it's a pixel value, that is always going to be the one specified in the styleproperty - unlessthat was overridden by an !importantstatement in a style sheet.

如果它是一个像素值,则它始终是style属性中指定的值-除非它被!important样式表中的语句覆盖。

jQuery docs for .css()

jQuery 文档 .css()

If you explicitlyneed the value specified in the element's styleproperty, use

如果您明确需要元素style属性中指定的值,请使用

$("#element_1")[0].style.top
$("#element_1")[0].style.left

unlike .css(), these values will be empty if they were not specified in the styleproperty.

与 不同.css(),如果这些值未在style属性中指定,则它们将为空。

(Using ID element_1, you can't have an ID named 1)

(使用 ID element_1,您不能有一个名为 的 ID 1

回答by Dustin Laine

You can use the CSSfunction:

您可以使用该CSS功能:

var topValue = $(this).css("top"); //Change the selector to meet your needs
var leftValue = $(this).css("left"); //Change the selector to meet your needs

回答by michaeltintiuc

using .css() will return an integer + px, but you can easily get a nice clean integer by doing this:

使用 .css() 将返回一个整数 + px,但您可以通过这样做轻松获得一个干净的整数:

var yourVar = parseInt($('selector').css('top'), 10);

回答by Tomalak

CSS properties are accessible through standard DOM properties:

CSS 属性可通过标准 DOM 属性访问:

alert( $("#theElement")[0].style.top ) // "250px"
alert( $("#theElement")[0].style.left ) // "250px"

As an aside, "1"is not a valid HTML element ID.

顺便"1"说一句,不是有效的 HTML 元素 ID。