简体   繁体   English

jQuery:选择样式属性?

[英]jQuery: select style attribute?

How to select with a specific style attribute? 如何选择具有特定样式属性?

<div style="width: 420px; text-align: left; margin-top: 10px; margin-bottom: 10px;">

I'm trying: 我尝试着:

$("div[style='width: 420px; text-align: left; margin-top: 10px; margin-bottom: 10px;']);  

but nothing gets selected. 但没有任何东西被选中

Your example works for me, in Chrome at least, once I corrected the typo of the missing " at the end of the line. 你的例子适用于我,至少在Chrome中,一旦我纠正了缺失的错误“在行尾。

$("div[style='width: 420px; text-align: left; margin-top: 10px; margin-bottom: 10px;']");

See this demo. 看这个演示。

To my knowledge, there's no way to do that using a jQuery selector, but you can use the filter() method instead: 据我所知,使用jQuery选择器无法做到这一点,但您可以使用filter()方法:

$("div").filter(function() {
    var $this = $(this);
    return $this.css("width") == "420px"
        && $this.css("text-align") == "left"
        && $this.css("margin-top") == "10px"
        && $this.css("margin-bottom") == "10px";
});

(This does not answer the question. However, if the person who wrote the HTML page had used classes instead of the style attribute, then the OP would not have this problem.) (这不回答问题。但是,如果编写HTML页面的人使用了类而不是style属性,那么OP就不会有这个问题。)

.foo { width: 420px; text-align: left; margin-top: 10px; margin-bottom: 10px; }

<div class="foo"> </div>

$("div.foo")

maybe try 也许试试

$('div').filter(function() {
    var self = $(this);
    return self.width() === 420 &&
           self.css('margin-top') === '10px' &&
           self.css('margin-bottom') === '10px' &&
           self.css('text-align') === 'left';
});

It would be easier however to select the element by one attribute such as id or css class, or by it's position to an element that has an id or css class. 然而,通过一个属性(例如id或css类)选择元素,或者通过它的位置选择具有id或css类的元素会更容易。

<h1>Hello header</h1>
<p style="color: red;">Hello My</p>
<script>
$(document).ready(function(){
$("p[style='color: red;']").fadeOut("10000",function(){
    $("h1").hide();
});
});
</script>

The style should be exact same as of in the 风格应该与中的完全相同

tag and $ selector 标签和$选择器

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

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