简体   繁体   English

添加类时CSS不透明度如何工作?

[英]How Does CSS Opacity Work When Adding Class?

I'm trying to get something to fade in using Jquery. 我正在尝试使用Jquery使某些东西淡出。 I am gathering the info via scrollTop(). 我正在通过scrollTop()收集信息。 So, when the scroll top equals the offset().top of the div, it will fadein. 因此,当滚动顶部等于div的offset()。top时,它将淡入。 Or just appear. 或只是出现。

#myDiv {
    background: #990000;
    height: 500px;
    width: 100%;
    overflow: hidden;
    opacity: 0;
}

.fade-in {
    opacity: 1.0;
}

There's my CSS. 这是我的CSS。

var winHeight = $(window).height();

    $(window).scroll(function() {
        var scrollTop = $(window).scrollTop();

        $("#myDiv").each(function() {
            var $this = $(this);
            var trigger = $(this).offset().top;

            if (scrollTop >= trigger) {
                $this.addClass("fade-in");
            }
        });
    });

And there is my Jquery. 还有我的Jquery。 The funny thing is that if I use $this.css it works fine. 有趣的是,如果我使用$ this.css,它可以正常工作。

I am just wondering how CSS and Jquery interact when it comes to opacity. 我只是想知道CSS和Jquery在不透明度方面如何交互。

The id-selector( #myDiv ) class gets more priority than the class-selector( .fade-in ) in css. id-selector( #myDiv.fade-in CSS中的class-selector( .fade-in )具有更高的优先级。 So the opacity property in the #myDiv gets more priority when your div has both the classes added. 因此,当您的div同时添加了两个类时, #myDiv的opacity属性将获得更高的优先级。 Just changing the .fade-in class a bit, your code should work fine. 只需.fade-in更改.fade-in类,您的代码就可以正常工作。

.fade-in {
    opacity: 1.0 !important;
}

Hope it helps :) 希望能帮助到你 :)

The jQuery .addClass() method just instantly adds the specified class to the element, and once it's added, the css rules are instantly applied just like they would be if you had added the class in the HTML. jQuery .addClass()方法立即将指定的类添加到元素中,并且一旦添加,就立即应用css规则,就像在HTML中添加该类一样。 There's absolutely nothing special or jQuery-specific about how the rules are applied, so opacity shouldn't be applied any differently than any other CSS rule would be. 规则的应用方式绝对没有任何特殊或jQuery特有的,因此不透明性的应用不应与其他CSS规则有所不同。 If you believe you're getting a different result when applying the rule via $(this).addClass("fade-in") rather than using $this.css, I'd suggest setting up a jsFiddle to show the issue so folks can take a look at it for you. 如果您认为通过$(this).addClass(“ fade-in”)而不是使用$ this.css来应用规则时会得到不同的结果,建议您设置一个jsFiddle来显示此问题,可以帮你看看。

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

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