我需要从"style"属性中提取一些内容:即"top"和"left"属性
<div style="top: 250px; left: 250px;" id="1" class="window ui-draggable">
有没有使用jQuery做这件事的最佳方式?有简便的方法吗,还是必须使用字符串函数?
我需要从"style"属性中提取一些内容:即"top"和"left"属性
<div style="top: 250px; left: 250px;" id="1" class="window ui-draggable">
有没有使用jQuery做这件事的最佳方式?有简便的方法吗,还是必须使用字符串函数?
这取决于您的需求。如果您需要计算出的值 - 例如浏览器在解析所有样式表后实际使用的值 - 使用
$("#element_1").css("top")
$("#element_1").css("left")
如果它是像素值,那么它始终是在style
属性中指定的那个值-除非在样式表中被!important
声明覆盖。
如果您需要显式使用元素style
属性中指定的值,请使用
$("#element_1")[0].style.top
$("#element_1")[0].style.left
.css()
不同,如果在 style
属性中未指定这些值,则它们将为空。element_1
,您不能拥有一个名为 1
的 ID)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
使用.css()将返回一个整数+px,但是您可以通过以下方式轻松获得一个漂亮的干净整数:
var yourVar = parseInt($('selector').css('top'), 10);
CSS属性可以通过标准DOM属性进行访问:
alert( $("#theElement")[0].style.top ) // "250px"
alert( $("#theElement")[0].style.left ) // "250px"
顺便提一下,"1"
不是一个有效的 HTML 元素 ID。
style
只会给你在style=
中明确指定的值。 - Pekka