Javascript jQuery:选择样式属性?

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

jQuery: select style attribute?

javascriptjqueryhtml

提问by mmierins

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.

但没有被选中。

回答by Orbling

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.

看到这个演示。

回答by Frédéric Hamidi

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";
});

回答by ?ime Vidas

(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 页面的人使用了类而不是样式属性,那么 OP 就不会出现这个问题。)

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

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

$("div.foo")

回答by Russ Cam

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 类的元素的位置来选择元素会更容易。

回答by Amal lal T L

<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

标签和 $ 选择器