jQuery 如何使用jquery获取css样式的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12273525/
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-26 11:30:23  来源:igfitidea点击:

how to get the value of css style using jquery

jquerycss

提问by iMarkDesigns

I'd like to know what type of method should I use to get the value of CSS style. I want to set it to jQuery so that I can create conditions to match on CSS "left" value.

我想知道我应该使用什么类型的方法来获取 CSS 样式的值。我想将它设置为 jQuery,以便我可以创建条件来匹配 CSS“左”值。

Here is the CSS and HTML tag with the style attributes.

这是带有样式属性的 CSS 和 HTML 标签。

<div class="items" style="left: -900px"> <span>some content here</span> </div>

Here is my jQuery code to get the value.

这是我获取值的 jQuery 代码。

<script>
  var n = $("items").css("left");
  if(n == -900){
    $(".items span").fadeOut("slow");
  }
</script>

I'd like to know if this method is correct because it is not working in my end. Thanks in advance for the little help.

我想知道这种方法是否正确,因为它最终不起作用。在此先感谢您的帮助。

Note: left value was dynamic, and it was changing to these value: -900px, -1800px, -2700px, -3600px, -4500px...

注意:左值是动态的,它正在更改为以下值:-900px、-1800px、-2700px、-3600px、-4500px...

回答by ?????

I doubt css understands leftby itself. You need to use it specifying position. You are using .css() correctly

我怀疑 cssleft自己理解。您需要使用它来指定位置。您正在正确使用 .css()

position: relative/absolute/whatever;
left: 900px;

heres a fiddle of it working

继承人的小提琴工作

http://jsfiddle.net/gFLZe/

http://jsfiddle.net/gFLZe/

and without the position here's what you get

没有这个职位,这就是你得到的

http://jsfiddle.net/gkkm5/

http://jsfiddle.net/gkkm5/

Change your if statement to be like this - with quotes around -900px

将您的 if 语句更改为这样 - 周围有引号 -900px

var n = $("items").css("left");

if(n == '-900px'){
    $(".items span").fadeOut("slow");
}

http://jsfiddle.net/gFLZe/1/

http://jsfiddle.net/gFLZe/1/

回答by Hammad Khan

You code is correct. replace items with .items as below

你的代码是正确的。用 .items 替换 items 如下

<script>
  var n = $(".items").css("left");
  if(n == -900){
    $(".items span").fadeOut("slow");
  }
</script>

回答by Skatox

Yes, you're right. With the css()method you can retrieve the desired css value stored in the DOM. You can read more about this at: http://api.jquery.com/css/

你是对的。使用该css()方法,您可以检索存储在 DOM 中的所需 css 值。您可以在以下位置阅读更多相关信息:http: //api.jquery.com/css/

But if you want to get its position you can check offset()and position()methods to get it's position.

但是如果你想得到它的位置,你可以检查offset()position()方法来获取它的位置。