简体   繁体   English

性能CSS规则与jQuery .toggleClass

[英]Performance css rules vs. jQuery .toggleClass

I'm running a wordpress theme, which has a sticky header. 我正在运行一个wordpress主题,该主题具有粘性标题。 I've built a subnav, which is displayed right below the header. 我建立了一个子导航,它显示在标题的正下方。 Whenever I use this subnav, the header should not stay sticky, instead the subnav should be sticky (already made with simple javascript addClass). 每当我使用此subnav时,标题都不应保持粘性,而应使subnav保持粘性(已经使用简单的javascript addClass进行了制作)。 I am only interested how to turn off the stickiness of the header the best way. 我只想知道如何以最佳方式关闭标头的粘性。

(1) Using CSS: One way is to use css and to override the classes, which make the header sticky. (1)使用CSS:一种方法是使用css并覆盖类,这会使标头变粘。 This already works, I've just changed the position fixed to static and disabled the placeholder, which avoids a gap in the content, when the position is set to fixed and the header is taken out of the flow. 这已经可行,我只是将位置固定为静态,并禁用了占位符,当位置设置为固定并且将标题从流程中移出时,可以避免内容出现空白。 Based on the circumstance that I want to use the subnav on many pages (ca. 70%) I would have to write one big css rule for targeting the relevant pages by their ids. 基于我要在许多页面上使用subnav的情况(大约70%),我将不得不编写一个大的CSS规则,以按其ID定位相关页面。 This leads to my thought that javascript may better on resources. 这导致我认为javascript可能会更好地利用资源。

(2) Using Javascript: I've wrote a small snippet of javascript, which easily removes the whole css-classes, when the ID of the subnav is present on the page: (2)使用Javascript:我写了一个小片段的javascript,当subnav的ID显示在页面上时,它很容易删除整个CSS类:

if(document.getElementById('subnavfullwidth')){
jQuery( '.header-sticky-height' ).toggleClass( 'header-sticky-height', 'false' );
jQuery( '.header-wrapper' ).toggleClass( 'header-is-sticky', 'false' );
jQuery( '.header' ).toggleClass( '.header-sticky-shadow', 'false' );
}

Simple as the title: Would the javascript be better or one big css-rule for the site performance? 标题很简单:对于网站性能,JavaScript会更好还是一个大的CSS规则? Is there a way to optimize my javascript or is it just okay? 有没有一种方法可以优化我的JavaScript还是可以吗?

Kind Regards! 亲切的问候!

I'd be more inclined to have one class added to '.header' (assuming that's the root element of the relevant area) named sticky, and change the class header to an id of header. 我更倾向于将一个类添加到“ .header”(假设这是相关区域的根元素)中,并将其命名为sticky,并将类头更改为头的id。

The way you have it written, you could gain a little performance by adding an id to '.header', and then chain methods together to limit the number of elements to have to search through. 编写方式中,可以在'.header'中添加一个id,然后将方法链接在一起以限制要搜索的元素数量,从而获得一些性能。

$('#header')
    .toggleClass('header-sticky-shadow', false)
    .find('.header-wrapper')
        .toggleClass('header-is-sticky', false)
    .end()
    .find('.header-sticky-height', false)
        .toggleClass('header-sticky-height', false);

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

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