简体   繁体   English

使用Javascript从具有属性选择器的CSS类更改属性的状态

[英]Change the state of a property from CSS class that has a attribute selector using Javascript

I have this HTML line: 我有以下HTML行:

<div id="content" class="slide" data-position="left" ></div>

and this CSS class with this [attribute] selector: 这个带有[attribute]选择器的CSS类:

.slide[data-position="left"] {
    display: none;
}

What I'm trying to do is after I click a button the css class will change like this using Javascript 我想做的是单击一个按钮后,css类将使用Java脚本进行更改,如下所示

.slide[data-position="left"] {
    display: block;
}

I tried different methods like adding a new class in the HTML line or adding a inline style="display: block;" 我尝试了其他方法,例如在HTML行中添加新类或添加内联style =“ display:block;”。 using Javascript: 使用Javascript:

$(".slide").attr('data-position', 'left').css({'display':'block'});

that generates 产生

<div id="content" class="slide" data-position="left" style="display: block;"></div>

but the .css() method doesn't help me at all because I want to change/override .slide[data-position="left"]. 但是.css()方法根本没有帮助我,因为我想更改/覆盖.slide [data-position =“ left”]。 The inline doesn't change anything in the CSS stylesheet. 内联不会更改CSS样式表中的任何内容。

I want to know how to change the state of a property for a specific css class that has a certain [attribute] selector. 我想知道如何更改具有特定[attribute]选择器的特定CSS类的属性状态。

I tried to google this issue but it seems that nobody has an answer for this. 我试图用谷歌搜索这个问题,但是似乎没有人对此有答案。

Any ideas? 有任何想法吗?

Thanks! 谢谢!

Instead of altering the CSS rule directly, you can give the element another class corresponding to another rule: 除了直接更改CSS规则,您还可以为元素提供与另一个规则相对应的另一个类:

.slide.active { display: block; }

or, if the attribute has importance still: 或者,如果属性仍然具有重要性:

.slide.active[data-position="left"] { display: block; }

That rule should go after the existing rule to ensure that a "slide" element that also has the "active" class will be visible. 该规则应遵循现有规则,以确保也显示“ active”类的“ slide”元素。

You'd add the class in JavaScript with 您可以使用以下方式在JavaScript中添加该类:

$("#content").addClass("active");

You can achieve this by changing your jQuery selector. 您可以通过更改jQuery选择器来实现。 At the moment you're using jQuerys attr method to target the data-position attribute and set its value to left. 目前,您正在使用jQuery的attr方法来定位data-position属性并将其值设置为left。 Instead you need to use the same attribute selector you previously used in your CSS declaration: .slide[data-position=left] 相反,您需要使用以前在CSS声明中使用的相同属性选择器: .slide[data-position=left]

What you need to do is change this: 您需要做的是更改此:

$(".slide").attr('data-position', 'left').css({'display':'block'});

to this: 对此:

$(".slide[data-position=left]").css({'display':'block'});

The complete jQuery would look like this: 完整的jQuery如下所示:

$("#clickMe").on("click",function(){

    $(".slide[data-position=left]").css({'display':'block'});

});

Demo 演示版

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

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